How to exclude some services like login, register from interceptor Angular 5, HttpClient

為{幸葍}努か 提交于 2019-12-22 02:56:45

问题


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));
  });
}

回答1:


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.




回答2:


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);

}




回答3:


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);
                    }
                }
            )
        );
    //}
}


来源:https://stackoverflow.com/questions/49746548/how-to-exclude-some-services-like-login-register-from-interceptor-angular-5-ht

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!