在ngOnInit Angular之前处理异步诺言 [英] Handle async promise before ngOnInit Angular

查看:271
本文介绍了在ngOnInit Angular之前处理异步诺言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回表数据的请求,该表需要像承诺一样等待,直到数据加载完毕.为了将数据加载到表中,我必须使用异步/等待,但这会弄乱所有其他函数/方法.

I have a request that returns data for a table, which needs to be handled like a promise to wait until the data has been loaded. In order to load the data into the table I have to use async/wait, but this messes up all other functions/methods.

如何在不对ngOnInit()使用异步/等待的情况下将数据存储在currentList中?还是有其他方法?

How to store the data in currentList without using async/wait on ngOnInit()? Or is there an other way?

async getEducationList(): Promise<any> {
  return this.educationList = await this.applicationClient.getEducations()
  .toPromise()
  .then((res) => {
    this.educationListAll = res;
  });
}

async ngOnInit() {
  await this.getEducationList();
  this.currentList = this.educationListAll;
}

注意-this.applicationClient.getEducations()是可观察的

Note - this.applicationClient.getEducations() is an Observable

推荐答案

通过将API调用包装在一个可观察的容器中,然后将代码从ngOnInit移到另一个函数initTable,解决了该问题.

Solved the issue by wrapping the API call in an observable and then moved the code from ngOnInit to another function initTable.

getEducationList(): Observable<Education[]> {
  return this.applicationClient.getEducations();
}

initTable(data) {
  // Some code to handle the data
}

ngOnInit() {
  this.getEducationList().toPromise().then(data => {
    this.loader = false;
    this.initTable(data);
  });
}

这篇关于在ngOnInit Angular之前处理异步诺言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆