Angular - Set headers for every request

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

    This is how I did for setting token with every request.

    import { RequestOptions, BaseRequestOptions, RequestOptionsArgs } from '@angular/http';
    
    export class CustomRequestOptions extends BaseRequestOptions {
    
        constructor() {
            super();
            this.headers.set('Content-Type', 'application/json');
        }
        merge(options?: RequestOptionsArgs): RequestOptions {
            const token = localStorage.getItem('token');
            const newOptions = super.merge(options);
            if (token) {
                newOptions.headers.set('Authorization', `Bearer ${token}`);
            }
    
            return newOptions;
        }
    }
    

    And register in app.module.ts

    @NgModule({
        declarations: [
            AppComponent
        ],
        imports: [
            BrowserModule
        ],
        providers: [
            { provide: RequestOptions, useClass: CustomRequestOptions }
        ],
        bootstrap: [AppComponent]
    })
    export class AppModule { }
    

提交回复
热议问题