我已经简要阅读了几篇文章和官方 Angular 指南,但它们似乎无法帮助我解决我的任务。这就是我想要的和所做的。
假设我有带有产品列表页面的 Angular 应用程序。此外,这个应用程序将来还会有类别列表页面和一些N列表页面。正如您所看到的,它们非常相似,并且有一个共同的组件 - 数据表。
<app-data-table [type]="'product'"></app-data-table>
其实现如下:
import {Component, Input, OnInit} from '@angular/core';
import {DataFactoryService} from "../data-factory.service";
@Component({
selector: 'app-data-table',
templateUrl: './data-table.component.html',
styleUrls: ['./data-table.component.css']
})
export class DataTableComponent implements OnInit {
@Input() type: string;
private data: any[];
constructor(private dataFactory: DataFactoryService) { }
ngOnInit(): void {
this.dataFactory.getServiceBy(this.type).selectAll();
}
}
正如您可能已经猜到的那样,我的意思是使该组件服务类型不可知。这就是我创建并注入它的原因DataFactory
:
import { Injectable } from '@angular/core';
import {ProductService} from "./product.service";
import {CategoryService} from "./category.service";
import {DataService} from "./data.service";
@Injectable({
providedIn: 'root'
})
export class DataFactoryService {
private serviceTokenMapping = {
"product": ProductService,
"category": CategoryService
};
constructor() { }
public getServiceBy(token: string): DataService {
return new this.serviceTokenMapping[token];
}
}
最后,我们有两个针对产品和类别的服务以及一些简单的基本抽象类:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export abstract class DataService {
abstract selectAll(): any[];
}
import { Injectable } from '@angular/core';
import {DataService} from "./data.service";
import {Product} from "./product";
@Injectable({
providedIn: 'root'
})
export class ProductService implements DataService {
constructor() {}
public selectAll(): Product[] {
console.log(`ProductService...`);
return [];
}
}
import { Injectable } from '@angular/core';
import {DataService} from "./data.service";
import {Category} from "./category";
@Injectable({
providedIn: 'root'
})
export class CategoryService implements DataService {
constructor() {}
public selectAll(): Category[] {
console.log(`CategoryService...`);
return [];
}
}
有趣的是,这个实现完全按照预期工作。因此,我将表格类型作为产品相关页面的产品传递,类别类型用于类别等。
问题是,从 Angular 风格(提供者、DI 等)的角度来看,我是否做了一些不正确的事情,我们是否有任何方法来实现这样的要求,使其更加 Angular 风格?