如何在类之外的Module文件的函数中插入Angular服务?

时间:2019-04-17 13:47:51

标签: angular typescript

声明模块类后,我的ast文件中有一些功能

app.module.ts

并在导入部分中使用它们

export function exportTranslateStaticLoader(http: HttpClient, config: RuntimeConfigLoaderService, transferState: TransferState, cookie: CookieService) {
  let apiUrl;
  if (environment.browser.symphonyApiUrl) {
    apiUrl = environment.browser.symphonyApiUrl;
  } else {
    const protocol = window.location.protocol;
    const host = window.location.host;
    apiUrl = `${protocol}//api.${host}`;
  }
  const link = environment.remoteTranslate ? `${apiUrl}/cms/locale/` : '/assets/i18n/';
  return new TranslateBrowserLoader(link, '.json', transferState, http, cookie);
}

我需要在此功能中使用某些服务(TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: exportTranslateStaticLoader, deps: [HttpClient, TransferState, CookieService] } }), ),如何使用?

1 个答案:

答案 0 :(得分:0)

您可以使用中间服务@Injectable来确保HttpClient和其他服务作为单例提供,
 那么TranslateBrowserLoader应该是此@Injectable
中函数的返回类型。

@Injectable()
export class TranslateLoader {

  constructor(
      private http: HttpClient,
      private config: RuntimeConfigLoaderService,
      private transferState: TransferState,
      private cookie: CookieService
       ) {}

// import exportTranslateStaticLoader

getTranslateStaticLoader() : TranslateBrowserLoader {
   return exportTranslateStaticLoader(
      this.http,
      this.config,
      this.transferState,
      this.cookie
     )
 }