我有向服务器执行请求的服务:
export class ExportDictionaryApiService {
constructor(private http: HttpClient) {}
public perform(): Observable<any> {}
}
还有一个类工厂:
export class ExportFactory {
public static createConcreteExcel(type: string) {
switch (type) {
case EReferenciesTypes.DictionaryType:
return new ExportDictionary();
}
}
}
工厂返回的具体类:
export class ExportDictionary implements IExport {
export(parameters: any) {
this.apiService
.perform().subscribe((response: IResponseDict) => {});
}
}
使用是:
ExportFactory.createConcreteExcel('full').export([...parameters]);
问题是:
具体的类应该使用具体的apiService
,现在class ExportDictionary
中没有现成的对象apiService
如何在具体类中传递? 我需要返回包含所有依赖项的就绪实例!
当然我可以在方法中注入(inject)准备好的对象:
ExportFactory.createConcreteExcel('full').export([...parameters], injectedApiService);
但我不知道 injctedApiService
直到我不创建具体工厂。
我也无法在里面创建对象:
export(parameters: any) {
new ExportDictionaryApiService()
.perform().subscribe((response: IResponseDict) => {});
}
因为ExportDictionaryApiService
需要依赖HttpClient
最佳答案
查看此工作示例 https://stackblitz.com/edit/angular-service-factory
p.s 您可以将字符串更改为枚举
解释
你需要一个工厂如下
@Injectable()
export class ExportFactoryService {
constructor(
@Inject('Export') private services: Array<IExport>
) { }
create(type: string): IExport {
return this.services.find(s => s.getType() === type);
}
}
服务接口(interface)
export interface IExport {
getType(): string; // this can be enum as well
export(parameters: any):any;
}
还有你的服务实现,我实现了两个服务
@Injectable()
export class ExportDictionaryService implements IExport {
constructor() { }
getType(): string {
return 'dictionary';
}
export(parameters: any):any {
console.log('ExportDictionaryService.export')
}
}
最重要的是,在 app.module 中提供多种服务
providers: [
ExportFactoryService,
{ provide: 'Export', useClass: ExportDictionaryService, multi: true },
{ provide: 'Export', useClass: ExportJsonService, multi: true }
]
这就是您获取服务实例的方式
constructor(private exportFactoryService: ExportFactoryService) {}
create() {
const exporter = this.exportFactoryService.create('dictionary');
exporter.export('full');
}
而且这种方式是Open-Closed的,可以通过增加新的服务来扩展,不需要修改已有的代码,没有if/else,switch/case语句,没有静态类,并且它是可单元测试的,您可以在每个导出器服务中注入(inject)任何需要的内容
关于angular - 如何在另一个内部使用服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57875590/