Skip to content

Instantly share code, notes, and snippets.

@a-patel
Last active November 16, 2018 18:17
Show Gist options
  • Select an option

  • Save a-patel/11d2891b06b27d19c946dd4cc2191e74 to your computer and use it in GitHub Desktop.

Select an option

Save a-patel/11d2891b06b27d19c946dd4cc2191e74 to your computer and use it in GitHub Desktop.
HTTP Interceptor in Angular
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