首页 > 解决方案 > 从服务文件到 app.module 获取值的最佳方法

问题描述

我希望导入从服务文件返回的值,例如服务文件是:

http.service.ts

selectedEnvironment() {
  return "abc";
}

但是我怎样才能将这个值放入我的app.module文件中。有首选方法吗?

我试过了:

应用程序模块

import { HttpService } from "./http.service";

export function HttpLoaderFactory(httpClient: HttpClient) {
  return new TranslateHttpLoader(httpClient, "./assets/" + HttpService.selectedEnvironment()+"/i18n/", ".json");
}

但它说“selectedEnvironment类型上不存在属性typeof HttpService”。

标签: angular

解决方案


如果是 Angular 服务

import { Injectable } from "@angular/core";

@Injectable()
export class YourHttpService {
  constructor() {}

  getEnvironment() {
    return "XYZ";
  }
}

您可以将服务指定为HttpLoaderFactory中的参数。请确保在 您的应用模块的deps: [HttpClient,YourHttpService ] 以及 providers providers: [YourHttpService]中指定了服务名称

export function HttpLoaderFactory(httpClient: HttpClient,httpService:YourHttpService) {
    console.log(httpService.getEnvironment());
  return new TranslateHttpLoader(httpClient);
}

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient,YourHttpService]
      }
    })
  ],
  providers: [YourHttpService],
  bootstrap: [AppComponent]
})
export class AppModule { }

示例代码 https://stackblitz.com/edit/transalate-vvmckq?file=src/app/app.module.ts


推荐阅读