在所有数据完成之前加载 Angular Page

分享于2023年05月08日 angular components typescript 问答
【问题标题】:Angular Page is loading before all the data is completed在所有数据完成之前加载 Angular Page
【发布时间】:2023-05-07 03:43:01
【问题描述】:

我在此频道上发布了几天前遇到的问题,但我仍然遇到同样的问题。

我目前正在开发一个 Angular 和 Typescript 应用程序。

我正在进行四个不同的 api 调用,获取数据并将其呈现到 UI 页面。

这个功能

public async getData(){
    let data = await this.http.get("google.com").toPromise();
    return data;
}

如果我只调用第一个 API,则从第一个 Api 获取数据并将其呈现到运行良好的 UI。我之所以按顺序需要它,是因为第一次调用需要在秒函数启动之前获取特定数据,并且它需要该数据来启动自己的进程,与第三和第四个函数相同。

第二个函数

 async getValueWithAsync(){
    let data = await this.http.get("google.com").toPromise();
    return data;
}

正在从第二个 Api 获取第二个数据,我正在像这样从 public async getData() 调用它。

const a = await this.getValueWithAsync().then(res => {alert(res)});

由于某种原因,数据正在返回,我可以通过 alert(res) 看到它,但 getData() 函数在我调用 getValueWithAsync() 时返回时没有数据,而如果我不调用它,它会附带数据,但是 getData() 所需的值是未定义的,这是有道理的。

我将再次感谢任何帮助。

  • 为什么要将 Observable 转换为 Promise?
  • 函数是否缺少 return 语句?也许这是打字稿的事情,但是当函数缺少 return 语句时,使用 JavaScript。它返回一个值 undefined
  • 有退货声明。我编辑了声明。
  • 因为 .then 方法缺少 return 语句,所以常量 a 将解析为 undefined

【解决方案1】:

试试这个..

this.getData().then(res => {
    alert(res);
    this.getValueWithAsync().then(res => {
        alert(res)
    });
});

注意:如果它不起作用,请尝试使用 observable

【讨论】: