Issue
I'm in the proces of adding an interceptor to my angular 6 project. To make calls to my API, I need to add a bearer token to all calls. Unfortunately the interceptor does not seem to be called. My code:
import { Injectable } from "@angular/core";
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from "@angular/common/http";
import { Observable } from "rxjs";
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>,
next: HttpHandler): Observable<HttpEvent<any>> {
//Retrieve accesstoken from local storage
const accessToken = localStorage.getItem("access_token");
//Check if accesToken exists, else send request without bearer token
if (accessToken) {
const cloned = req.clone({
headers: req.headers.set("Authorization",
"Bearer " + accessToken)
});
console.log('Token added to HTTP request');
return next.handle(cloned);
}
else {
//No token; proceed request without bearer token
console.log('No token added to HTTP request');
return next.handle(req);
}
}
}
Does anyone know what could be causing this issue? Thanks in advance.
Solution
You use the right way to intercept.
For people who use interceptor, you need to do 2 modifications :
Interceptor in service
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse }
from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
@Injectable()
export class MyInterceptor implements HttpInterceptor {
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(req).do(evt => {
if (evt instanceof HttpResponse) {
console.log('---> status:', evt.status);
console.log('---> filter:', req.params.get('filter'));
}
});
}
}
Provide HTTP_INTERCEPTOR
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
(...)
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: MyInterceptor, multi: true }
],
Read this article for more details. It's pretty good
Answered By - Pterrat
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.