Angular - Set headers for every request

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

    For Angular 5 and above, we can use HttpInterceptor for generalizing the request and response operations. This helps us avoid duplicating:

    1) Common headers

    2) Specifying response type

    3) Querying request

    import { Injectable } from '@angular/core';
    import {
      HttpRequest,
      HttpHandler,
      HttpEvent,
      HttpInterceptor,
      HttpResponse,
      HttpErrorResponse
    } from '@angular/common/http';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/operator/do';
    
    @Injectable()
    export class AuthHttpInterceptor implements HttpInterceptor {
    
      requestCounter: number = 0;
      constructor() {
      }
    
      intercept(request: HttpRequest, next: HttpHandler): Observable> {
    
        request = request.clone({
          responseType: 'json',
          setHeaders: {
            Authorization: `Bearer token_value`,
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
          }
        });
    
        return next.handle(request).do((event: HttpEvent) => {
          if (event instanceof HttpResponse) {
            // do stuff with response if you want
          }
        }, (err: any) => {
          if (err instanceof HttpErrorResponse) {
            // do stuff with response error if you want
          }
        });
      }
    }
    

    We can use this AuthHttpInterceptor class as a provider for the HttpInterceptors:

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { AppComponent } from './app.component';
    import { AppRoutingModule } from './app.routing-module';
    import { AuthHttpInterceptor } from './services/auth-http.interceptor';
    import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        AppRoutingModule,
        HttpClientModule,
        BrowserAnimationsModule,
      ],
      providers: [
        {
          provide: HTTP_INTERCEPTORS,
          useClass: AuthHttpInterceptor,
          multi: true
        }
      ],
      exports: [],
      bootstrap: [AppComponent]
    })
    export class AppModule {
    }
    

提交回复
热议问题