2

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

Community
  • 1
  • 1
Fernando Leal
  • 9,875
  • 4
  • 24
  • 46

2 Answers2

2

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

yurzui
  • 205,937
  • 32
  • 433
  • 399
  • RequestMethod was a detail, the major problem was the order of the class declaration. Perfect correction, thank you. Despite being stupid mistake is very hard to identify it, nothing it made sense to see your reply. – Fernando Leal Sep 30 '16 at 20:34
0

you may look at below StackOverflow questions, they talk in depth about this,

What is httpinterceptor equivalent in angular2?

Interceptors in Angular2

Madhu Ranjan
  • 17,334
  • 7
  • 60
  • 69
  • Ok I had already seen some of these topics, these questions and answers covering the previous approach of how this should be done (angular previous RC 5), as exemplified in [the beginning of the question](http://stackoverflow.com/q/39798231/2290538). But in my case the problem is specifically with the current version of the angular (`angular 2.0 final`). – Fernando Leal Sep 30 '16 at 19:33