Angular - Set headers for every request

前端 未结 19 1642
[愿得一人]
[愿得一人] 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:32

    You can create your own http client with some authorization header:

    import {Injectable} from '@angular/core';
    import {HttpClient, HttpHeaders} from '@angular/common/http';
    
    @Injectable({
      providedIn: 'root'
    })
    export class HttpClientWithAuthorization {
    
      constructor(private http: HttpClient) {}
    
    createAuthorizationHeader(bearerToken: string): HttpHeaders {
      const headerDict = {
        Authorization: 'Bearer ' + bearerToken,
      }
      return new HttpHeaders(headerDict);
    }
    
    get(url, bearerToken) {
      this.createAuthorizationHeader(bearerToken);
      return this.http.get(url, {
        headers: this.createAuthorizationHeader(bearerToken)
      });
    }
    
    post(url, bearerToken, data) {
      this.createAuthorizationHeader(bearerToken);
      return this.http.post(url, data, {
        headers: this.createAuthorizationHeader(bearerToken)
      });
    }
    }
    

    And then inject it instead of HttpClient in your service class:

    @Injectable({
      providedIn: 'root'
    })
    export class SomeService {
    
      constructor(readonly httpClientWithAuthorization: HttpClientWithAuthorization) {}
    
      getSomething(): Observable {
        return this.httpClientWithAuthorization.get(url,'someBearer');
      }
    
      postSomething(data) {
        return this.httpClientWithAuthorization.post(url,'someBearer', data);
      }
    }
    
        

    提交回复
    热议问题