I'm trying to find a way to intercept and modify all HTTP requests made by Angular by adding custom headers. In previous releases prior to angular2 RC5, this was achieved by extending the BaseRequestOptions
like this:
class MyOptions extends BaseRequestOptions {
Authorization: string = 'Bearer ' + localStorage.getItem('tokenName');
}
bootstrap(AppComponent,
[HTTP_PROVIDERS,
{ provide: RequestOptions, useClass: MyOptions },
appRouterProviders,
disableDeprecatedForms(),
provideForms(),
]).catch(err => console.error(err));
Currently using version 2.0 final
, I found a suggestion on how to implement this in the newer version which looks something like this:
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
providers: [
{ provide: RequestOptions, useClass: MyOptions }
],
bootstrap: [ AppComponent ]
})
export class AppModule {
}
@Injectable()
export class MyOptions extends RequestOptions {
constructor() { super({method: RequestMethod.Get, headers: new Headers()}); }
}
However, when implementing this, an error is thrown:
TypeError: Can not read property 'merge' of null
. Check out this example for more details.
Note: The implementation of
MyOptions
mirrors that ofBaseRequestOptions
, as copying it resolves the issue. View this example for comparison.