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

How to use service inside another?

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

export class ExportDictionaryApiService {
  constructor(private http: HttpClient) {}
  public perform(): Observable<any> {}
}

还有一个class工厂:

export class ExportFactory {
  public static createConcreteExcel(type: string) {
    switch (type) {
      case EReferenciesTypes.DictionaryType:
        return new ExportDictionary();
    }
  }
}

以及由工厂 return 编辑的具体 class:

export class ExportDictionary implements IExport {
  export(parameters: any) {
     this.apiService
      .perform().subscribe((response: IResponseDict) => {});
  }
}

使用是:

ExportFactory.createConcreteExcel('full').export([...parameters]);

问题是:

混凝土class应该使用混凝土apiService,现在class ExportDictionary

里面没有现成的对象apiService

具体如何传递class? 我需要 return 个包含所有依赖项的现成实例!

我当然可以在方法中注入准备好的对象:

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);
  }

}

您的服务界面

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的说法,没有静态 class,并且它是可单元测试的,您可以在每个导出器服务中注入任何需要的东西