Angular - Set headers for every request

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

    To answer, you question you could provide a service that wraps the original Http object from Angular. Something like described below.

    import {Injectable} from '@angular/core';
    import {Http, Headers} from '@angular/http';
    
    @Injectable()
    export class HttpClient {
    
      constructor(private http: Http) {}
    
      createAuthorizationHeader(headers: Headers) {
        headers.append('Authorization', 'Basic ' +
          btoa('username:password')); 
      }
    
      get(url) {
        let headers = new Headers();
        this.createAuthorizationHeader(headers);
        return this.http.get(url, {
          headers: headers
        });
      }
    
      post(url, data) {
        let headers = new Headers();
        this.createAuthorizationHeader(headers);
        return this.http.post(url, data, {
          headers: headers
        });
      }
    }
    

    And instead of injecting the Http object you could inject this one (HttpClient).

    import { HttpClient } from './http-client';
    
    export class MyComponent {
      // Notice we inject "our" HttpClient here, naming it Http so it's easier
      constructor(http: HttpClient) {
        this.http = httpClient;
      }
    
      handleSomething() {
        this.http.post(url, data).subscribe(result => {
            // console.log( result );
        });
      }
    }
    

    I also think that something could be done using multi providers for the Http class by providing your own class extending the Http one... See this link: http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html.

提交回复
热议问题