0

I am following this one here How do I set default Http Headers for all requests in Ionic 2?

This works fine and in all http calls it pass the headers I put. But my problem is when I inject any service to this MyRequestOptions constructor this service is undefined and cant use it...

Anyone know why? I need to inject here my custom AuthService to also put the JWT token.

Community
  • 1
  • 1
Nick Doulgeridis
  • 583
  • 1
  • 16
  • 31

1 Answers1

2

It's because the BaseReqestOptions uses @Injectable, which cases the BaseRequestOptions constructor to be called instead of your subclass constructor. So you could either:

Use a factory

providers: [{
  provide: RequestOptions,
  deps: [ Config ],
  useFactory: (config: Config) => {
    return new DefaultRequestOptions(config);
  }
}]

This will allow you to create the service yourself, without Angular trying to inject it. Or you could

Extend RequestOptions instead

@Injectable()
class DefaultRequestOptions extends RequestOptions {
  constructor(public config: Config) {
    super({method: RequestMethod.Get, headers: new Headers()})

    this.headers.append('data', this.config.data);
  }
}

RequestOptions isn't decorated with @Injectable. And if you look at the source code for BaseRequestOptions, you see all it does is the same thing we are doing above (with the super call).

I need to inject here my custom AuthService to also put the JWT token

You need to be careful with this if AuthService is injecting Http. You might get a circular dependency error (because Http uses RequestOptions and your RequestOptions needs Http). One way to handle this is to inject the Injector, instead Http into the service. Then just get the Http from the Injector.

Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720