angular - 如何在另一个内部使用服务?

标签 angular typescript oop angular8

我有向服务器执行请求的服务:

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/

相关文章:

angular - 找不到 'AppModule' 的 NgModule 元数据

c++ - 如何创建使用重写函数的非成员函数?

android - Cordova angular2应用程序中的"Exception: Error during instantiation of t! Primary outlet already registered."

css - Angular Material : How to set each mat-horizontal-stepper stepper icon with different background color in TS

javascript - TSC 正在根据 tsconfig.json 文件的方向编译 node_modules 和类型声明文件

跨多文件的 Typescript 命名空间

reactjs - React 事件处理程序中带有 Typescript 的动态对象键

javascript - 如何在javascript中获取某个类的所有静态成员的列表

c# - C#中如何防止非法ICloneable<T>继承?

angular - websocket 的严重性能问题 - 每条消息都会触发 Angular 更改检测