【发布时间】:2019-10-13 05:01:56
【问题描述】:
我有一个简单的配置服务,我在我的 app.shared.module.ts 中使用 APP_INITIALIZER 令牌:
ConfigService,
{
provide: APP_INITIALIZER,
useFactory: (configService: ConfigService) =>
() => configService.getStuff(),
deps: [ConfigService],
multi: true
},
这会执行订阅(config.service.ts):
settings: any;
getStuff() {
this.getSettings()
.subscribe(data => {
this.settings = data);
});
}
getSettings(): Observable<ISettings> {
return (this.httpClient
.get<ISettings>(this.localbaseUrl)
.pipe(
catchError(this.errorHandlerSerevice.handleError)
)) as any;
}
然后我将此服务注入其他服务(通过它们的构造函数 - 我不喜欢),并且在应用启动时一切正常:
constructor(){
this.settings = this.configService.settings;
}
当我转到主页并从那里刷新应用程序时很好。 调用逻辑并返回数据。 但是,当我刷新使用该组件并调用构造函数的特定页面时,数据返回似乎很晚,因此我在这里返回未定义:
this.settings = this.configService.settings;
我猜'接线'是错误的......
有什么建议可以解决吗?
【问题讨论】:
-
我相信你正在关注Dave Bush: where to store angular configurations。他没有提到的一个警告是,即使有了这个建议,您仍然有义务为每个环境更改 index.html 的
<base href>的唯一目的编译每个环境。确保你没有白白执行它。 -
@Stavm 是的,我根据环境进行编译。回到我最初的问题 - 坦率地说,我对(1)这种实现和(2)我在这里缺乏选择以及(3)Promise 在这里产生如此大的影响这一事实以及(4)我不能依赖于通常的页面生命周期。这很烦人。
标签: angular typescript