Angular 9 HttpClient: Ignore header on one call

人盡茶涼 提交于 2021-01-29 19:29:53

问题


I am trying to make requests to the google books api using HttpClient in Angular 9. I want to disable the Authorization header in a single get request.

My problem is that I am already logged in and my requests have an Authorization header which causes calls to the google books API to return a 401 error. I can replicate the same in postman as well. Adding a key parameter to the request call (where I pass my API key) makes no difference.

With Authorization header disabled I get a 200 status code:

With Authorization header enabled I get a 401 status code:

And finally, my request in the browser:

This is where I add my Authorization header to httpClient:

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const currentUser = this.localStorageService.getCurrentUser();
    if (currentUser) {
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${currentUser.split('"')[3]}`
        }
      });
    }
    return next.handle(request);
  }

And finally, the constructor where I inject httpClient and the call:

  constructor(public httpClient: HttpClient) {
  }

  public requestBook(isbn: string): Observable<any> {
    return this.httpClient.get(`https://www.googleapis.com/books/v1/volumes?q=${isbn}`);
  }

My question is: I want to disable the Authorization header in the get Request in requestBook but keep it anywhere else. I thought I'd create a new httpClient instance but that also had the Authorization Header.


回答1:


I am against using interceptor to manipulate HTTP request in an Angular project unless it's absolutely essential and won't be changed across different resources requests or endpoints.

In your case, it's obviously not the case because you want Authorization header to be removed in one specific request.

Of course, you can do some silly tweaks to quickly make it work such as

if (currentUser && !request.url.includes('www.googleapis.com/books/v1/volumes')) {
  request = request.clone({
    setHeaders: {
      Authorization: `Bearer ${currentUser.split('"')[3]}`
    }
  });
}

But I would recommend create your own angular Service instead of manipulating global requests with the interceptor.

So basically instead of calling this.httpClient.get(), you now calling this.myApiService.get() instead which simply wrap a HttpClient service with some additional business logic that suit your needs.

Then when you want to disable sending Authorization header, have this flag in your own method and use it something like this:

this.myApiService.get('my-resource', { noAuth: true });

This is more maintainable compare to Blackbox interceptor that sometimes drive your colleagues crazy.



来源:https://stackoverflow.com/questions/61560189/angular-9-httpclient-ignore-header-on-one-call

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