Handle async promise before ngOnInit Angular

白昼怎懂夜的黑 提交于 2019-12-08 05:08:19

问题


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()? 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


回答1:


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
}



回答2:


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);
  });
}


来源:https://stackoverflow.com/questions/54925816/handle-async-promise-before-ngoninit-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!