Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
@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
}
}).catch(err => {
if (err instanceof HttpErrorResponse {
if (err.status === 401) {
// JWT expired, go to login
// Observable.throw(err);
}
}
})
}
}
@mackelito

This comment has been minimized.

Copy link

mackelito commented Aug 16, 2017

Perhaps I´m missing something here but I get
Argument of type '(err: any) => void' is not assignable to parameter of type '(err: any, caught: Observable<void>) => ObservableInput<{}>'. Type 'void' is not assignable to type 'ObservableInput<{}>'.

@mackelito

This comment has been minimized.

Copy link

mackelito commented Aug 16, 2017

Also, is the constructor(private router: Router) {} really needed?

@SamuelSlf

This comment has been minimized.

Copy link

SamuelSlf commented Aug 17, 2017

@mackelito, you have to return an Observable and add a parentheses in your if.
Example:

if (err instanceof HttpErrorResponse) {
            if (err.status === 401) {
               // JWT expired, go to login
               return Observable.throw(err);
            }
          }

Your second question was "Also, is the constructor(private router: Router) {} really needed?", you dont need, but can redirect to any route like "access denied"

@SamuelMarks

This comment has been minimized.

Copy link

SamuelMarks commented Aug 29, 2017

You're missing a closing parentheses on line 13, fixed: https://gist.github.com/SamuelMarks/fec9a736764c49b4790adbb99aca54a5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.