I have an http
observable like so, in my UserService
:
logout() {
return this.http.delete(this.baseUrl + url, {
headers: this.headers()
}).map((res: IResponse) => {
var json = res.json();
json.headers = res.headers;
return json;
}).subscribe((response) => {
//DO SOMETHING, THEN ----
return res;
});
}
I have created an observable, and created a subscription (response
) which is the returned success value.
Now, in my component, I want to call UserService.logout()
and THEN navigate to a new route:
logout() {
this.userService.logout();
this.router.navigate(['LandingPage']);
}
Obviously, this could happen asynchronously and I may end up navigating before I logout.
Using promises, I could do something like this:
this.userService.logout().then(() => {
this.router.navigate(['LandingPage']);
});
How can I do the same thing with observables? In my UserService
class I want to create an observable, subscribe to it, do some stuff on success or on error, THEN navigate from my view component.
You can't wait for an
Observable
to finish because its stream might continue indefinitely. But you could callrouter.navigate
inside thesubscribe
method:If this isn't sufficient,
subscribe
returns aSubscription
whoseunsubscribe
method stops waiting for theObservable
's data. So if you have to, you can wait for a timeout period and callunsubscribe
.Logout need to return an Observable not a Subscription. For example:
For more information about operators/methods: https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/observable.md
You can actually make
logout
method return a promise and use it as normal. It doesn't have to be Observable:Observable object has method finally, try it. Don't forget to import first:
Your logout() would be:
If you really wanted to use promise:
in component.ts