[英]Angular async ngOnInit instantiating a needed property
I have a property in an Angular component, instantiated through a service inside async ngOnInit
:我在 Angular 组件中有一个属性,通过
async ngOnInit
内部的服务实例化:
txtItems: TextItems[];
constructor(private textItemService: TextItemService) {}
async ngOnInit() {
// await on promise
this.txtItems = await this.textItemService.getAllAsync();
}
where getAllAsync
returns a promise:其中
getAllAsync
返回 promise:
async getAllAsync(): Promise<TextItems[]> {
return await this.http.get<TextItems[]>(this.url).toPromise();
}
ngOnInit
runs asynchronously so that the page doesn't have to hang until items are loaded (which is a good thing), but sometimes this.txtItems
is accessed from the template before it has finished loading, which results in an exception. ngOnInit
异步运行,因此页面在加载项目之前不必挂起(这是一件好事),但有时this.txtItems
在完成加载之前从模板访问,这会导致异常。
I can make ngOnInit
not async
, but then the page will load slowly.我可以使
ngOnInit
不是async
,但是页面会加载缓慢。
Should I use txtItems: Promise<TextItems[]>
or something like that, and then access it from everywhere using the async
pipe?我应该使用
txtItems: Promise<TextItems[]>
或类似的东西,然后使用async
pipe 从任何地方访问它吗? What is the correct approach when waiting for async services?等待异步服务时正确的方法是什么?
This is a classic case of converting an observable to a promise without any substantiated advantages.这是将 observable 转换为 promise 的经典案例,没有任何经证实的优势。 And given that the output from the HTTP request is used only in the template, you could return the observable from service and use it's value in the template using
async
pipe.并且鉴于 HTTP 请求中的 output 仅在模板中使用,您可以从服务中返回 observable 并使用
async
Z20826A3CB51D6C7D9C219C7F4BFZ5E 在模板中使用它的值。
Service服务
getAllAsync(): Observable<TextItems[]> {
return this.http.get<TextItems[]>(this.url);
}
Component零件
public txtItems$: Observable<TextItems[]>;
constructor(private textItemService: TextItemService) {
this.txtItems$ = this.textItemService.getAllAsync(); // <-- no `await`, only assignment
}
Template模板
<ng-container *ngIf="(txtItems$ | async) as txtItems">
<!-- use `txtItems` -->
</ng-container>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.