问题
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