Angular - Set headers for every request

前端 未结 19 1649
[愿得一人]
[愿得一人] 2020-11-22 07:43

I need to set some Authorization headers after the user has logged in, for every subsequent request.


To set headers for a particular request,



        
19条回答
  •  死守一世寂寞
    2020-11-22 08:39

    After some investigation, I found the final and the most easy way is to extend BaseRequestOptions which I prefer.
    The following are the ways I tried and give up for some reason:
    1. extend BaseRequestOptions, and add dynamic headers in constructor(). It can not work if I login. It will be created once. So it is not dynamic.
    2. extend Http. Same reason as above, I can not add dynamic headers in constructor(). And if I rewrite request(..) method, and set headers, like this:

    request(url: string|Request, options?: RequestOptionsArgs): Observable {
     let token = localStorage.getItem(AppConstants.tokenName);
     if (typeof url === 'string') { // meaning we have to add the token to the options, not in url
      if (!options) {
        options = new RequestOptions({});
      }
      options.headers.set('Authorization', 'token_value');
     } else {
      url.headers.set('Authorization', 'token_value');
     }
     return super.request(url, options).catch(this.catchAuthError(this));
    }
    

    You just need to overwrite this method, but not every get/post/put methods.

    3.And my preferred solution is extend BaseRequestOptions and overwrite merge() :

    @Injectable()
    export class AuthRequestOptions extends BaseRequestOptions {
    
     merge(options?: RequestOptionsArgs): RequestOptions {
      var newOptions = super.merge(options);
      let token = localStorage.getItem(AppConstants.tokenName);
      newOptions.headers.set(AppConstants.authHeaderName, token);
      return newOptions;
     }
    }
    

    this merge() function will be called for every request.

提交回复
热议问题