Injected dependency is undefined when extending BaseRequestOptions

后端 未结 2 1365
面向向阳花
面向向阳花 2021-01-22 01:15

I am extending BaseRequestOptions in Angular2 to add headers for each request. I also have a Config class that supplies key/value pairs based on the do

相关标签:
2条回答
  • 2021-01-22 01:51

    This is actually much easier than peeskillet's answer. When defining your provider also specify the dependencies for that provider so it would look like:

    providers: [
    {
        provide: RequestOptions,
        useClass: DefaultRequestOptions,
        deps: [Config]
    };
    
    0 讨论(0)
  • 2021-01-22 01:54

    Provider classes don't require @Injectable() unless they require constructor parameters to be injected. In your case it does. This is why Angular recommends to always use it on your providers, whether or not you require injections. Maybe for this exact reason, where you forget, when it's needed.

    @Injectable()
    export class DefaultRequestOptions extends BaseRequestOptions {
    

    After testing

    It seems this still doesn't work. I've seen this problem is a result of extending a class that already uses @Injectable() (which BaseRequestOptions does). In this case, the parent constructor is called instead of the extending class'. If you extend RequestOptions instead (which is not decorated with @Injectable()) then it would work

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

    Notice the super() call. This is all that BaseRequestOptions does.

    If you wanted to keep it the way it currently is, using BaseRequestOptions, then you could use a factory, instead of letting Angular create it

    {
      provide: RequestOptions,
      deps: [ Config ],
      useFactory: (config: Config) => {
        return new DefaultRequestOptions(config);
      }
    }
    
    0 讨论(0)
提交回复
热议问题