0

I am using HttpInterceptor to add Auth token and the issue is that the interceptor is adding the token for first request and after that it stops working. Here is my Interceptor Service

import { Injectable } from '@angular/core';
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from "@angular/common/http";
import {Observable} from "rxjs/internal/Observable";
import {CommonService} from "./common.service";

@Injectable({
  providedIn: 'root'
})
export class AuthInterceptorService implements HttpInterceptor {

  constructor(private auth: CommonService) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authToken = this.auth.getAuthToken();
    const authReq = req.clone({ setHeaders: { Authorization: 'Bearer '+authToken.access_token} });
    return next.handle(authReq);
  }
}

Here is the App Module provider section

providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: AuthInterceptorService,
    multi: true
  }],

Let me know what is the wrong with the code.

user3739018
  • 2,319
  • 3
  • 12
  • 21
  • 1
    Are you seeing any errors? – wctiger Aug 22 '18 at 13:44
  • You declare it at the providers array and you use "providedIn: 'root'" at the injectable annotation. Did you try to remove the providedIn from @Injectable? – Stefan Großmann Aug 22 '18 at 13:54
  • I am getting following errors 401 (Unauthorized) Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. – user3739018 Aug 22 '18 at 13:54
  • removing "providedIn: 'root'" did not help. – user3739018 Aug 22 '18 at 13:57
  • 2
    Seems that you have classic CORS problem. Your interceptor has nothing to do with it. – Stanisalv Dontsov Aug 22 '18 at 14:17
  • To work around CORS, depends what type of backend you use, you may have to set CORS policy in your API. Beside, if you are testing from Chrome, check out this answer which can help bypass Chrome's CORS check: https://stackoverflow.com/a/3177718/5395603 – wctiger Aug 22 '18 at 14:52

0 Answers0