我想我理解我遇到的問題,但很難找出最佳解決方案。我有一個 Ionic / Angular 應用程式,它通過各種服務類進行 API 呼叫,所有這些服務類都由父“DataService”類呼叫。
一旦用戶登錄到我的應用程式,他們就會被重定向到“TaskList”組件。該組件呼叫DataService.getData()應該使用適當的資料填充 DataService 中的幾個陣列。這段代碼可以在下面看到:
export class TaskListPage implements OnInit {
...
ngOnInit() {
this.dataService.getData().then(() => {
this.workOffers = this.dataService.getWorkOffers();
this.confirmedWorkOrderDates = this.dataService.getConfirmedWorkOrderDates();
console.log("Client Task List WO: " JSON.stringify(this.workOffers));
});
}
}
但是,在加載頁面后,workOffers 陣列為空 [],從 console.log 行可以看出。
我知道這是因為TaskListPage 在DataService 有機會在該陣列中存盤任何daya 之前以某種方式呼叫DataService.getWorkOffers()。我嘗試向 getData 函式添??加承諾,以強制在 getData 執行完成后執行 getWorkOffers() ,但它不起作用。
這是 DataService.getData():
getData() {
return new Promise<void>((resolve) => {
this.workOffers = new Array();
this.updates = new Array();
this.tasks = new Array();
this.shifts = new Array();
this.confirmedWorkOrderDates = new Array();
// Get USER object of user logged in
this.userService.getUser(this.currentUserId).subscribe(async (user: User) => {
this.userLoggedIn = user;
this.currentUserId = user.id;
this.getClientData().then(() => {
resolve();
});
}
});
});
}
getClientData 是另一種呼叫其他幾個服務類的方法:
getClientData() {
return new Promise<void>((resolve) => {
this.workOfferService.getClientBookedOffers(this.currentUserId)
.subscribe((workOffers: WorkOffer[]) => {
for (let wo in workOffers) {
// Push workOffer to array
this.workOffers.push(workOffers[wo]);
...[ More Service calls]
}
});
resolve();
});
}
我一定是錯誤地使用了 Promises,因為據我了解 getData 應該在 TaskList 呼叫 getWorkOffers 之前完成執行(并因此填充 DataService.workOffers[])。
uj5u.com熱心網友回復:
我不知道您在這里使用的 Angular 版本是什么。在我看來,它可以使用 Obversable e2e 來簡化。Angular HttpService 已經在最新版本中提供了這個。
在我看來,您正在盡快解決 getClientData 上的承諾。當您在訂閱之外呼叫 resolve 時,GetClientData Promise 將回傳 WorkOffer 為空。
我試圖解釋的一個小例子 https://stackblitz.com/edit/angular-ivy-weug88?file=src/app/app.component.ts
這應該可以解決您的用例:
getClientData() {
return new Promise<void>((resolve) => {
this.workOfferService.getClientBookedOffers(this.currentUserId)
.subscribe((workOffers: WorkOffer[]) => {
for (let wo in workOffers) {
// Push workOffer to array
this.workOffers.push(workOffers[wo]);
...[ More Service calls]
}
// now only resolve when WorkOffer are fully loaded
resolve();
});
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/420563.html
標籤:
