Fernando Fernando - 11 months ago 123
TypeScript Question

Intercept all HTTP requests from angular2

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
) was that way, for example:

class MyOptions extends BaseRequestOptions {
Authorization: string = 'Bearer ' + localStorage.getItem('tokenName');

{ provide: RequestOptions, useClass: MyOptions },
]).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:

imports: [ BrowserModule ],
declarations: [ AppComponent ],
providers: [
{ provide: RequestOptions, useClass: MyOptions }
bootstrap: [ AppComponent ]
export class AppModule {

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
is the same as
, copied, because if you use
{Provide: RequestOptions, useClass: BaseRequestOptions}
, everything works, as can be seen this example.

Answer Source

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