Last active
November 16, 2018 18:17
-
-
Save a-patel/11d2891b06b27d19c946dd4cc2191e74 to your computer and use it in GitHub Desktop.
HTTP Interceptor in Angular
This file contains hidden or 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 { HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http"; | |
| import { Injectable } from "@angular/core"; | |
| import { TokenService } from "../services/token.service"; | |
| @Injectable() | |
| export class CustomHttpInterceptor implements HttpInterceptor { | |
| constructor(private readonly tokenService: TokenService) { } | |
| intercept(request: HttpRequest<any>, next: HttpHandler) { | |
| let url = request.url; | |
| if (!url.startsWith("http")) { | |
| url = document.getElementsByTagName("base").item(0).href + url; | |
| } | |
| request = request.clone({ | |
| setHeaders: { Authorization: `Bearer ${this.tokenService.get()}` }, | |
| url | |
| }); | |
| return next.handle(request); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment