【发布时间】:2018-08-16 05:47:01
【问题描述】:
我希望 Angular 等到我的 loadConfig() 函数解析后再构建其他服务,但事实并非如此。
app.module.ts
export function initializeConfig(config: AppConfig){
return () => config.loadConfig();
}
@NgModule({
declarations: [...]
providers: [
AppConfig,
{ provide: APP_INITIALIZER, useFactory: initializeConfig, deps: [AppConfig], multi: true }
] })
export class AppModule {
}
app.config.ts
@Injectable()
export class AppConfig {
config: any;
constructor(
private injector: Injector
){
}
public loadConfig() {
const http = this.injector.get(HttpClient);
return new Promise((resolve, reject) => {
http.get('http://mycoolapp.com/env')
.map((res) => res )
.catch((err) => {
console.log("ERROR getting config data", err );
resolve(true);
return Observable.throw(err || 'Server error while getting environment');
})
.subscribe( (configData) => {
console.log("configData: ", configData);
this.config = configData;
resolve(true);
});
});
}
}
some-other-service.ts
@Injectable()
export class SomeOtherService {
constructor(
private appConfig: AppConfig
) {
console.log("This is getting called before appConfig's loadConfig method is resolved!");
}
}
SomeOtherService 的构造函数在从服务器接收数据之前被调用。这是一个问题,因为 SomeOtherService 中的字段没有设置为正确的值。
如何确保SomeOtherService 的构造函数仅在loadConfig 的请求得到解决后才被调用?
【问题讨论】:
-
您在哪里使用 SomeOtherService。可以复制吗?
-
你能在 stackblitz 上发布一个示例吗? @yurzi 发布了一个似乎与您拥有的代码完全相同的代码并且它可以正常工作。另外,您的代码中是否有任何 HttpInterceptors?
-
不要在那里使用
.catch,因为 APP_INITIALIZER 有它自己的 catch 可以停止 APP。另外,使用来自@AlesD 答案的.toPromise() -
我遇到了类似的问题:(我试图在 stackblitz 中重现它,但没有成功。这令人沮丧。你终于解决了你的问题吗?你找到任何可能的原因了吗?如何解决?
标签: angular dependency-injection angular-services bootstrapping angular-di