'Angular Component not getting proper data from Service
I think I understand the issue I am having, yet am having a hard time figuring out the best solution. I have an Ionic / Angular app which makes API calls through a variety of Service classes, all of these Service classes are called by a parent "DataService" class.
Once a user logs into my application, they are redirected to a "TaskList" component. This component calls DataService.getData() which should populate several arrays within DataService with the appropriate data. This code can be seen below:
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));
});
}
}
However, upon the page being loaded, the workOffers array is empty [] as can be seen from the console.log line.
I know this is because the TaskListPage is somehow calling DataService.getWorkOffers() before DataService has had a chance to store any daya within that array. I've tried adding promises to the getData function to force the execution of getWorkOffers() to happen after getData is done executing, but it doesn't work.
Here is 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 is another method that calls several other service classes:
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();
});
}
I must be using the Promises incorrectly, because from what I understand getData should finish executing (and thus populate DataService.workOffers[]) before TaskList calls getWorkOffers.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
