I'm looking for a way to intercept all HTTP requests made by the angular and add some headers. In releases prior to angular2 RC5
(before NgModule
) was that way, for example:
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));
I am currently in version 2.0 final
and as research on how this would be implemented in this version would be something similar to 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()}); }
}
It displays the following error: TypeError: Can not read property 'merge' of null
. As can be seen this example.
Note: The implementation of
MyOptions
is the same asBaseRequestOptions
, copied, because if you useBaseRequestOptions
in{Provide: RequestOptions, useClass: BaseRequestOptions}
, everything works, as can be seen this example.
I see two mistakes in your code
You didn't import RequestMethod
You have to declare your extented class MyOptions
before NgModule
decorator
This way your demo will look like Plunker