tom*_*3pr 4 typescript angular
我有一个简单的配置服务,已在 app.shared.module.ts 中使用 APP_INITIALIZER 令牌进行连接:
ConfigService,
{
provide: APP_INITIALIZER,
useFactory: (configService: ConfigService) =>
() => configService.getStuff(),
deps: [ConfigService],
multi: true
},
Run Code Online (Sandbox Code Playgroud)
这将执行订阅(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;
}
Run Code Online (Sandbox Code Playgroud)
然后我将此服务注入其他服务(通过它们的构造函数 - 我不喜欢),并且应用程序启动时一切正常:
constructor(){
this.settings = this.configService.settings;
}
Run Code Online (Sandbox Code Playgroud)
当我进入主页并从那里刷新应用程序时,一切都很好。调用逻辑并返回数据。然而,当我刷新使用该组件并调用构造函数的特定页面时,数据返回似乎已经很晚了,因此我在这里返回了 undefined :
this.settings = this.configService.settings;
Run Code Online (Sandbox Code Playgroud)
我猜“接线”是错误的......
有什么建议如何解决吗?
为了让 Angular等待您的自定义APP_INITIALIZER完成,它必须返回一个Promise. 你的getStuff方法没有返回任何内容,这意味着 Angular 不会等待this.settings设置。
您可以使用toPromise将您的转换Observable为Promise. 这是一个基本示例:
getStuff(): Promise<void> {
return this.getSettings()
.toPromise()
.then(data => {
this.settings = data;
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1954 次 |
| 最近记录: |