Today I was discussing with a colleague what’s the best options to always set some header data for your HTTP requests. Here is my solution…
Create a new TypeScript class that inherits from BaseRequestOptions:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Injectable, Inject, LOCALE_ID} from '@angular/core'; | |
import {RequestOptions, BaseRequestOptions} from '@angular/http'; | |
@Injectable() | |
export class DefaultRequestOptions extends BaseRequestOptions { | |
constructor(@Inject(LOCALE_ID) locale: string) { | |
super(); | |
// Set the default 'Content-Type' header | |
this.headers.set('Content-Type', 'application/json'); | |
this.headers.set('Accept', 'application/json'); | |
this.headers.set('Accept-Language', locale ? locale : 'nl-BE'); | |
this.headers.set('X-Requested-By', 'My-App'); | |
} | |
} |
Note: In this example I injected a LOCALE_ID to capture the culture set in the application.
Next step is to create a provider that replaces the default RequestOptions:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const RequestOptionsProvider = {provide: RequestOptions, useClass: DefaultRequestOptions}; |
Last step is to register the DefaultRequestOptionsProvider in your module:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { NgModule, LOCALE_ID } from '@angular/core'; | |
import { HttpModule } from '@angular/http'; | |
import { RequestOptionsProvider } from './helpers/default-request-options'; | |
@NgModule({ | |
declarations: [ | |
], | |
imports: [ | |
HttpModule, | |
RouterModule | |
], | |
providers: [ | |
RequestOptionsProvider | |
], | |
bootstrap: [AppComponent], | |
}) | |
export class AppModule { | |
} |