Skip to content

Instantly share code, notes, and snippets.

@isaacrlevin
Created August 18, 2017 19:17
Show Gist options
  • Save isaacrlevin/b76c594709130d146a752d550c1ce770 to your computer and use it in GitHub Desktop.
Save isaacrlevin/b76c594709130d146a752d550c1ce770 to your computer and use it in GitHub Desktop.
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class JWTInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (req.method === 'DELETE' || req.method === 'POST' || req.method === 'PUT') {
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
if (currentUser && currentUser.token) {
req = req.clone({
setHeaders: {
authorization: 'Bearer ' + currentUser.token
}
});
}
}
return next.handle(req);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment