【问题标题】:Angular async ngOnInit instantiating a needed propertyAngular async ngOnInit 实例化所需的属性
【发布时间】: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&lt;TextItems[]&gt; 或类似的东西,然后使用async 管道从任何地方访问它吗?等待异步服务的正确方法是什么?

【问题讨论】:

  • 请说明getAllAsync()是如何定义的。
  • @MichaelD:抱歉,已更新。它只是返回一个围绕 http get 的承诺。

标签: angular async-await promise ngoninit


【解决方案1】:

这是一个经典案例,将 observable 转换为 Promise,但没有任何经证实的优势。鉴于 HTTP 请求的输出仅在模板中使用,您可以从服务返回 observable 并使用 async 管道在模板中使用它的值。

服务

getAllAsync(): Observable<TextItems[]> {
   return this.http.get<TextItems[]>(this.url);
}

组件

public txtItems$: Observable<TextItems[]>;

constructor(private textItemService: TextItemService) {
  this.txtItems$ = this.textItemService.getAllAsync();   // <-- no `await`, only assignment
}

模板

<ng-container *ngIf="(txtItems$ | async) as txtItems">
  <!-- use `txtItems` -->
</ng-container>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-30
    • 2018-03-19
    • 2016-05-08
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    相关资源
    最近更新 更多