Angular - Set headers for every request

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

    Create a custom Http class by extending the Angular 2 Http Provider and simply override the constructor and request method in you custom Http class. The example below adds Authorization header in every http request.

    import {Injectable} from '@angular/core';
    import {Http, XHRBackend, RequestOptions, Request, RequestOptionsArgs, Response, Headers} from '@angular/http';
    import {Observable} from 'rxjs/Observable';
    import 'rxjs/add/operator/map';
    import 'rxjs/add/operator/catch';
    
    @Injectable()
    export class HttpService extends Http {
    
      constructor (backend: XHRBackend, options: RequestOptions) {
        let token = localStorage.getItem('auth_token'); // your custom token getter function here
        options.headers.set('Authorization', `Bearer ${token}`);
        super(backend, options);
      }
    
      request(url: string|Request, options?: RequestOptionsArgs): Observable {
        let token = localStorage.getItem('auth_token');
        if (typeof url === 'string') { // meaning we have to add the token to the options, not in url
          if (!options) {
            // let's make option object
            options = {headers: new Headers()};
          }
          options.headers.set('Authorization', `Bearer ${token}`);
        } else {
        // we have to add the token to the url object
          url.headers.set('Authorization', `Bearer ${token}`);
        }
        return super.request(url, options).catch(this.catchAuthError(this));
      }
    
      private catchAuthError (self: HttpService) {
        // we have to pass HttpService's own instance here as `self`
        return (res: Response) => {
          console.log(res);
          if (res.status === 401 || res.status === 403) {
            // if not authenticated
            console.log(res);
          }
          return Observable.throw(res);
        };
      }
    }
    

    Then configure your main app.module.ts to provide the XHRBackend as the ConnectionBackend provider and the RequestOptions to your custom Http class:

    import { HttpModule, RequestOptions, XHRBackend } from '@angular/http';
    import { HttpService } from './services/http.service';
    ...
    @NgModule({
      imports: [..],
      providers: [
        {
          provide: HttpService,
          useFactory: (backend: XHRBackend, options: RequestOptions) => {
            return new HttpService(backend, options);
          },
          deps: [XHRBackend, RequestOptions]
        }
      ],
      bootstrap: [ AppComponent ]
    })
    

    After that, you can now use your custom http provider in your services. For example:

    import { Injectable }     from '@angular/core';
    import {HttpService} from './http.service';
    
    @Injectable()
    class UserService {
      constructor (private http: HttpService) {}
    
      // token will added automatically to get request header
      getUser (id: number) {
        return this.http.get(`/users/${id}`).map((res) => {
          return res.json();
        } );
      }
    }
    

    Here's a comprehensive guide - http://adonespitogo.com/articles/angular-2-extending-http-provider/

提交回复
热议问题