Reputation: 81
I'm trying to create an 'interceptor' for AuthHttp service (angular2-jwt). I created a class that extends AuthHttp and use that instead. So far it seems to work fine. What I want to do now is, if the server responds with a 401 code is to force a logout within my app and ignore following subscriptions (I'm not sure if these subscriptions are executed sequentially so I don't know if what I'm gonna ask is possible).
As I just want to show an error in this scenario, I just need from this subscription to abort the queue and ignore further subscriptions. Here's the code I got so far for the get method:
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
let observable = super.get(url, options);
observable.subscribe(
() => { },
(error: Response) => {
if (error.status === 401) {
// Logout and ignore all other subscriptions
}
}
);
return observable;
}
Is this possible?
Thanks!
Upvotes: 0
Views: 689
Reputation: 5357
You can unsubscribe. The subscribe
method returns a Subscription
object. You can use that to unsubscribe:
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
let observable = super.get(url, options);
let subscription = observable.subscribe(
() => { },
(error: Response) => {
if (error.status === 401) {
// Logout and ignore all other subscriptions
subscription.unsubscribe();
}
}
);
return observable;
}
Upvotes: 2