Angular - Set headers for every request

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

    Although I'm answering it very late but it might help someone else. To inject headers to all requests when @NgModule is used, one can do the following:

    (I tested this in Angular 2.0.1)

    /**
     * Extending BaseRequestOptions to inject common headers to all requests.
     */
    class CustomRequestOptions extends BaseRequestOptions {
        constructor() {
            super();
            this.headers.append('Authorization', 'my-token');
            this.headers.append('foo', 'bar');
        }
    }
    

    Now in @NgModule do the following:

    @NgModule({
        declarations: [FooComponent],
        imports     : [
    
            // Angular modules
            BrowserModule,
            HttpModule,         // This is required
    
            /* other modules */
        ],
        providers   : [
            {provide: LocationStrategy, useClass: HashLocationStrategy},
            // This is the main part. We are telling Angular to provide an instance of
            // CustomRequestOptions whenever someone injects RequestOptions
            {provide: RequestOptions, useClass: CustomRequestOptions}
        ],
        bootstrap   : [AppComponent]
    })
    

提交回复
热议问题