Intercept all HTTP requests from angular2

2

I am looking for a way to intercept all HTTP requests made by angular and add some headers . In versions prior to angular2 RC5 (before NgModule ) it was this 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'm currently in the 2.0 final version and as search on how this would be implemented in this version , it would look 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()}); }
}

This displays the following error: TypeError: Cannot read property 'merge' of null . As can be seen in this example .

  

Note: The implementation of MyOptions is the same as BaseRequestOptions ", copied because if you use BaseRequestOptions in { provide: RequestOptions, useClass: BaseRequestOptions} , everything works, as can be observed in this example .

    
asked by anonymous 30.09.2016 / 20:32

0 answers