Last active
December 27, 2018 16:39
-
-
Save dancornilov/778fccb9fea005b9db56aca30f812374 to your computer and use it in GitHub Desktop.
Token HttpInterceptor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Injectable} from '@angular/core'; | |
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http'; | |
import {Observable} from 'rxjs/Observable'; | |
import {AuthService} from '../services/auth.service'; | |
@Injectable() | |
export class TokenInterceptor implements HttpInterceptor { | |
constructor(private auth: AuthService) { | |
} | |
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { | |
const token = localStorage.getItem('token'); // Without Auth Service | |
// const token = this.auth.getToken(); // With Auth Service (AuthService is custom service which u can create) | |
if (token) { | |
request = request.clone({ | |
setHeaders: { | |
authToken: `Bearer ${token}` | |
} | |
}); | |
} | |
return next.handle(request); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment