Skip to content

Instantly share code, notes, and snippets.

@danielcrisp
Last active April 5, 2021 20:15
Show Gist options
  • Save danielcrisp/ced7d092b07efa609285ba5f0823ca60 to your computer and use it in GitHub Desktop.
Save danielcrisp/ced7d092b07efa609285ba5f0823ca60 to your computer and use it in GitHub Desktop.
TokenInterceptor - Async HTTP Interceptors with Angular 4
import { Injectable } from '@angular/core';
import { HttpErrorResponse, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/mergeMap';
import { AuthService } from './auth.service';
@Injectable()
export class TokenInterceptor implements HttpInterceptor {
constructor (private auth: AuthService) {}
intercept (request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return this.auth.getUser()
.mergeMap((user: User) => {
if (user) {
// clone and modify the request
request = request.clone({
setHeaders: {
Authorization: `Bearer ${user.access_token}`
}
});
}
return next.handle(request)
// new
.do(() => {
// success
}, (err: any) => {
// error
if (err instanceof HttpErrorResponse) {
if (err.status === 401) {
// redirect user to login
this.auth.login();
}
}
});
});
}
}
@bipoza
Copy link

bipoza commented Jul 28, 2020

Thank you! This has helped me a lot.

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