Reputation: 3680
I would like to wait for all my http request to be completed before doing something.
Before Angular 5, I was using promises and Promise.All
.
With Angular 5 and the new HttpClient
, I transformed my promises into observables. If I understand correctly, I now have to use forkJoin
to replace the Promise.All
.
But this is a problem because forkJoin
expect Observables as parameters, but I already subscribe to those in the code
ngOnInit() {
forkJoin([this.getTemplates(), this.getHistory()]).subscribe(
results => {
this.isLoading = false;
}
);
}
getTemplates(): Observable<any> {
return this.notifService.getTemplateList()
.subscribe(
response => {
if (response.code === 0) {
this.templateList = response.data;
}
else {
this.openSnackBar(response.formatError());
}
},
error => {
this.openSnackBar(error);
});
}
I can't do the logic inside the subscription of the forkJoin
because those method (getTemplates()
& getHistory()
) need to be standalone and called seperatly in other processes.
So, what can I do to be sure that all the subscriptions are done ?
By the way, the code above doesn't compile because the method getTemplates()
return a Subscription
and not an Observable
Upvotes: 2
Views: 5810
Reputation: 13346
Use map
Instead of subscribe
in getTemplates
:
getTemplates(): Observable<any> {
return this.notifService.getTemplateList()
.map(response => {
/* ... */
return reponse;
});
}
Upvotes: 2