Angular 2 inject service into extended class(BaseRequestOptions)

后端 未结 2 911
野性不改
野性不改 2021-01-27 04:04

I have the following code that extends the BaseRequestOptions class:

import { Injectable } from \'@angular/core\';

@Injectable()
export class AppReq         


        
相关标签:
2条回答
  • 2021-01-27 04:28

    This is very similar to the question I answered here: Injected dependency is undefined when extending BaseRequestOptions

    When defining your provider also define the dependencies needed, so the object in your providers definition would look like:

    {
     provide: RequestOptions,
     useClass: AppRequestOptions,
     deps: [ServiceA]
    }
    
    0 讨论(0)
  • 2021-01-27 04:50

    There is an open bug for this: https://github.com/angular/angular/issues/9758.

    Whereas the metadata for dependency injection is correctly set, the element isn't provided to the class instance at the constructor level.

    @Injectable()
    export class AppRequestOptions extends BaseRequestOptions {
      constructor(private serviceA:ServiceA) {       
        super();        
        console.log(Reflect.getMetadata('design:paramtypes', AppRequestOptions));
        console.log(Reflect.getMetadata('parameters', AppRequestOptions));
      }
    
      (...)
    }
    

    See this plunkr for more details: https://plnkr.co/edit/hcqAfsI7u88jbjScq6m3?p=preview.

    Edit

    It will work if you use the RequestOptions class instead of the BaseRequestOptions one:

    @Injectable()
    export class AppRequestOptions extends RequestOptions {
      constructor(private serviceA:ServiceA) {       
        super();        
      }   
    
      (...)
    }
    

    See this plunkr: https://plnkr.co/edit/laP04kqUCOR5qbFgo0iM?p=preview.

    0 讨论(0)
提交回复
热议问题