How to exclude some services like login, register from interceptor Angular 5, HttpClient
Although #Fussel's answer (above) works, it's often not good practice to include the interceptor service in every component module. It's counter intuitive and counter productive. We want the interceptor in one place and work for all http requests. One way is to exclude the header binding in the intercept() function based on the url.
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const re = /login/gi;
// Exclude interceptor for login request:
if (req.url.search(re) === -1 ) {
req = req.clone({
setHeaders: {
Authorization: `Bearer ${localStorage.getItem('authToken')}`
}
});
}
return next.handle(req);
}
To give this an answer not only in comments as requested ;-)
To exclude some services (or even the same services used in different components) from an interceptor it's best to split your application into modules and provide the interceptor only in modules where it's needed. For example after logging in or inside of an admin area.
The interceptor may be even provided for single components using the @Component
declaration's providers
property.
I had to solve this same. The division into modules is very expensive for me. And the #DragoRaptor solution is not suitable when you have several points where you need to "jump" the interceptor
My solution is unorthodox, but maybe it will serve someone else.
It simply consists of:
- Include one more parameter in the request
- Check for this parameter in the interceptor
- Remove the parameter
Invocation example
public searchPersons(term: string): Observable<any> {
return this.http.get('person/', { params: { dni: term, spinner: 'no' } });
}
Interceptor example
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// check if you have the parameter 'spinner'
const spinner = request.params.get('spinner');
if (spinner && spinner === 'no') {
// remove parameter
request.params.delete('spinner');
// jump the interceptor
return next.handle(request);
}
// Execute interceptor
}
}