I am trying to call two observables, with the response from second I manipulate the first and then return a new observable.
return this.http.get(requestUrl)
.map((response: User) => {
sessionManager.currentUser = response;
return this.isFirstTimeUser(response.id);
})
.do((response: any) => {
console.log(response);
sessionManager.currentUser.firstTimeLogin = response === 'true';
return Observable.create(sessionManager.currentUser);
})
.toPromise();
isFirstTimeUser(response.id) is another function that returns an observable.
private isFirstTimeUser(userId: number): Observable<any> {
const requestUrl = 'someUrl';
return this.http.get(requestUrl, {responseType: 'text'});
}
All I want to do is get the user object from the first http call, make another request using the user's id
in the second call and then after I get back the response from the second observable, I update a property of the first response and return the updated first response. How do I achieve this? What rxjs function should I be looking at?
You were close in your example.
You want to use switchMap
which unsubscribes to the incoming observable, and subscribes to the next observable.
return this.http.get(requestUrl)
.switchMap((response: User) => {
sessionManager.currentUser = response;
return this.isFirstTimeUser(response.id);
})
.map((response: any) => {
console.log(response);
sessionManager.currentUser.firstTimeLogin = response === 'true';
return sessionManager.currentUser;
})
.toPromise();
The response will be passed to isFirstTimeuser()
and the following .map()
will be applied to the observabled returned by that function.
It's called switchMap
because the observable returned by this.http.get()
is unsubscribed and the next observable is used. This won't be a problem with this.http.get()
, but keep in mind that switchMap
only works for the first emitted value.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments