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 n
In my case interceptor wasn't getting involved for service calls because I had imported HttpClientModule
multiple times, for different modules.
Later I found that HttpClientModule
must be imported only once. Doc ref
Hope this helps!
In my case i had a post method like this:
this.http.post<any>(this.authUrl, JSON.stringify({username: username, password: password})).pipe(
map((response: any) => {
let token: any = response.token;
if (token) {
localStorage.setItem('currentUser', 'value' }));
return response;
} else {
return null;
}
}),
catchError((error:any) => {return observableThrowError(error.json().error || 'Server error')})
);
Because the map
method could return null
the interceptor stopt intercepting the requests made with this post method call. Don't ask me why this is so, but as soon as i replace null
with say response
everything started working again.
If you have a providers array for a module then you have to define the HTTP_INTERCEPTORS too for that module then only it will intercept the requests under that module.
e.g:
providers: [
// singleton services
PasswordVerifyService,
{ provide: HTTP_INTERCEPTORS, useClass: AppInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptorService, multi: true }
]
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
In my case, I had to import both HTTP_INTERCEPTORS, HttpClientModule
in same module.