【发布时间】:2021-06-03 03:46:27
【问题描述】:
我在 Angular 组件中有一个属性,通过 async ngOnInit 内部的服务实例化:
txtItems: TextItems[];
constructor(private textItemService: TextItemService) {}
async ngOnInit() {
// await on promise
this.txtItems = await this.textItemService.getAllAsync();
}
getAllAsync 返回一个承诺:
async getAllAsync(): Promise<TextItems[]> {
return await this.http.get<TextItems[]>(this.url).toPromise();
}
ngOnInit 异步运行,因此页面在加载项目之前不必挂起(这是一件好事),但有时在完成加载之前从模板访问 this.txtItems,这会导致例外。
我可以让ngOnInit 不是async,但是页面会加载缓慢。
我应该使用txtItems: Promise<TextItems[]> 或类似的东西,然后使用async 管道从任何地方访问它吗?等待异步服务的正确方法是什么?
【问题讨论】:
-
请说明
getAllAsync()是如何定义的。 -
@MichaelD:抱歉,已更新。它只是返回一个围绕 http get 的承诺。
标签: angular async-await promise ngoninit