加载模板之前等待响应

问题描述 投票:0回答:1

我有一个角度应用程序,它在

ngOnInit()
上进行服务器调用并返回结果。然后,我使用结果填充模板中的模型。我的模板在调用完成之前加载,给我一个未定义的错误。如何确保调用在模板加载之前完成?

ngOnInit(): void {
    this.GetCurrentSelectedProducts();
}

GetCurrentSelectedProducts() {
    this.proposalService.getCurrentSelectedProducts(this.proposalId).subscribe(response => {
      this.productResponse = response.result;
    });
}

..

<select [(ngModel)]="productResponse.Id">
angular typescript
1个回答
0
投票

这是预期的行为。由于您的 API 调用是异步的,因此当您的模板加载完成时,它将在将来的某个时间解决。

要修复,您可以尝试这些

  1. 根据 Angular 版本在模板
    *ngIf
    @if
    中放置条件检查,并尝试显示一些加载图形。
  2. 如果需要在渲染模板之前加载数据,则在路由器的'resolve'中进行api调用
© www.soinside.com 2019 - 2024. All rights reserved.