Skip to content

Instantly share code, notes, and snippets.

@chenkie
Last active April 18, 2018 10:47
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save chenkie/ca8344b685aa03b7d282a6c9632f0744 to your computer and use it in GitHub Desktop.
Save chenkie/ca8344b685aa03b7d282a6c9632f0744 to your computer and use it in GitHub Desktop.
import {
HttpInterceptor,
HttpRequest,
HttpResponse,
HttpHandler,
HttpEvent
} from '@angular/common/http';
import 'rxjs/add/operator/map';
@Injectable()
class JWTInterceptor implements HttpInterceptor {
constructor(private router: Router) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req).map((event: HttpEvent<any>) => {
if (event instanceof HttpResponse) {
// do stuff with response if you want
}
}, (err: any) => {
if (err instanceof HttpErrorResponse {
if (err.status === 401) {
// redirect to login
}
}
});
}
}
@kuceraf
Copy link

kuceraf commented Jul 25, 2017

It does not work for me - while server returns 403 Forbidden it does not go to error callback.
Instead it triggers the successful callback and the event is typeof object (which is useless in reaction on error response). The object looks like this:
{type:0}

Could you help me with that, please?

@grzegorz-skowronski
Copy link

@kuceraf

changing
return next.handle(req).map((event: HttpEvent) => {
to
return next.handle(req).do((event: HttpEvent) => {

fixed it for me. Refer to https://angular.io/guide/http#intercepting-all-requests-or-responses

@toddmotto
Copy link

toddmotto commented Aug 15, 2017

@Greg5ki, thanks for posting up the .map() => .do() change, that worked perfectly for me (.map() was only executing the first success arg, not the error).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment