[英]Best way to get a value from service file to app.module
我希望导入从服务文件返回的值,例如,服务文件为:
http.service.ts
selectedEnvironment() {
return "abc";
}
但是如何将这个值放入我的app.module
文件中。 有没有首选的方法?
我试过了:
app.module
import { HttpService } from "./http.service";
export function HttpLoaderFactory(httpClient: HttpClient) {
return new TranslateHttpLoader(httpClient, "./assets/" + HttpService.selectedEnvironment()+"/i18n/", ".json");
}
但是它说“ typeof HttpService
类型type上不存在属性selectedEnvironment
”。
如果是角度服务
import { Injectable } from "@angular/core";
@Injectable()
export class YourHttpService {
constructor() {}
getEnvironment() {
return "XYZ";
}
}
您可以在HttpLoaderFactory中将服务指定为参数。 请确保在您的应用程序模块的deps:[HttpClient,YourHttpService ]和提供程序提供程序:[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
在app.module.ts中添加此
providers: [HttpService]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.