Skip to content

Instantly share code, notes, and snippets.

@NetanelBasal
Last active August 29, 2017 06:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save NetanelBasal/ec02f28433ec51eafcd30686a8921a7c to your computer and use it in GitHub Desktop.
Save NetanelBasal/ec02f28433ec51eafcd30686a8921a7c to your computer and use it in GitHub Desktop.
@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
Copy link

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
Copy link

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

@samuelsherrer
Copy link

@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
Copy link

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