i wanted to exclude some services using interceptor.
app.module.js
providers: [
UserService,
RolesService,
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
},
],
Login.service.ts
return this.httpClient.post(this.appUrl + '/oauth/token', body.toString(), { headers, observe: 'response' })
.map((res: Response) => {
const response = res.body;
this.storeToken(response);
return response;
})
.catch((error: any) => {
ErrorLogService.logError(error);
return Observable.throw(new Error(error.status));
});
}
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.
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);
}
I had the similar problem. Once implemented interceptor hunt all http requests anyway. It was in my code about if i have, or not access token. If I haven't than interceptors token parametar has to be set to ""(empty string). Than everything goes.
In the interceptor fn code it seems like this:
intercept(
request: HttpRequest<any>,
next: HttpHandler**strong text**
): Observable<HttpEvent<any>> {
//how to update the request Parameters
**let token : string;
let currentUser : any = JSON.parse(localStorage.getItem('currentUser'));
if (currentUser){
token = currentUser.access_token;
}else{token = ""}**
console.log("Token dobavljen sa localStorage.getItem: ", token);
if (token) {
request = request.clone({ headers: request.headers.set('Authorization', 'Bearer ' + token) });
}
if (!request.headers.has('Content-Type')) {
request = request.clone({ headers: request.headers.set('Content-Type', 'application/json') });
}
request = request.clone({ headers: request.headers.set('Accept', 'application/json') });
//logging the updated Parameters to browser's console
console.log("Before making api call : ", token);
return next.handle(request).pipe(
tap(
event => {
//logging the http response to browser's console in case of a success
if (event instanceof HttpResponse) {
console.log("api call success :", event);
}
},
error => {
//logging the http response to browser's console in case of a failuer
if (event instanceof HttpResponse) {
console.log("api call error :", event);
}
}
)
);
//}
}
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
}
}