简体   繁体   English

在ngOnInit Angular之前处理异步诺言

[英]Handle async promise before 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. 为了将数据加载到表中,我必须使用异步/等待,但这会弄乱所有其他函数/方法。

How to store the data in currentList without using async/wait on ngOnInit()? 如何在不使用ngOnInit()上的异步/等待的情况下将数据存储在currentList中? 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;
}

Note - this.applicationClient.getEducations() is an Observable 注意-this.applicationClient.getEducations()是可观察的

try this way 尝试这种方式

async ngOnInit() : Promise<void> {
  this.currentList = await this.applicationClient.getEducations().toPromise();
  this.initTable(data);
}

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

Solved the issue by wrapping the API call in an observable and then moved the code from ngOnInit to another function initTable. 通过将API调用包装在一个可观察的对象中,然后将代码从ngOnInit移到另一个函数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);
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM