在 ngOnInit Angular 之前处理异步承诺
Handle async promise before ngOnInit Angular
我有一个 returns 数据用于 table 的请求,需要像承诺等待数据加载完成一样处理。为了将数据加载到 table,我必须使用 async/wait,但这会弄乱所有其他 functions/methods。
如何在不使用 async/wait on ngOnInit() 的情况下将数据存储在 currentList 中?或者有其他方法吗?
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() 是一个 Observable
试试这个方法
async ngOnInit() : Promise<void> {
this.currentList = await this.applicationClient.getEducations().toPromise();
this.initTable(data);
}
initTable(data) {
// Some code to handle the data
}
通过将 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);
});
}
我有一个 returns 数据用于 table 的请求,需要像承诺等待数据加载完成一样处理。为了将数据加载到 table,我必须使用 async/wait,但这会弄乱所有其他 functions/methods。
如何在不使用 async/wait on ngOnInit() 的情况下将数据存储在 currentList 中?或者有其他方法吗?
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() 是一个 Observable
试试这个方法
async ngOnInit() : Promise<void> {
this.currentList = await this.applicationClient.getEducations().toPromise();
this.initTable(data);
}
initTable(data) {
// Some code to handle the data
}
通过将 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);
});
}