Angular - Set headers for every request

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

    There were some changes for angular 2.0.1 and higher:

        import {RequestOptions, RequestMethod, Headers} from '@angular/http';
        import { BrowserModule } from '@angular/platform-browser';
        import { HttpModule }     from '@angular/http';
        import { AppRoutingModule } from './app.routing.module';   
        import { AppComponent }  from './app.component';
    
        //you can move this class to a better place
        class GlobalHttpOptions extends RequestOptions {
            constructor() { 
              super({ 
                method: RequestMethod.Get,
                headers: new Headers({
                  'MyHeader': 'MyHeaderValue',
                })
              });
            }
          }
    
        @NgModule({
    
          imports:      [ BrowserModule, HttpModule, AppRoutingModule ],
          declarations: [ AppComponent],
          bootstrap:    [ AppComponent ],
          providers:    [ { provide: RequestOptions, useClass: GlobalHttpOptions} ]
        })
    
        export class AppModule { }
    

提交回复
热议问题