angular 2 injection not work in inheritance

2019-03-03 08:29发布

问题:

recently we upgraded from Angular 2.0 to 2.4 and since then we have problems with inheritance. all dependencies gets undefined if we call the child.

  • the child don't have a constructor, what means it uses the father constructor.

this is the code:

@Injectable()
export class ChildComponent extends ParentComponent {

}


export class ParentComponent implements OnInit, AfterViewInit, AfterViewChecked {

    constructor(protected _activitySettingsControlService: ActivitySettingsControlService,
                protected _changeDetectionRef: ChangeDetectorRef,
                protected _elemRef: ElementRef,
                protected _apiService: ApiService) {

    }

all dependencies are undefind in this way.

what can be the reason ?

回答1:

Without a complete example, we can only guess. Consider using the below as a starting point for the requested minimal, complete and verifiable example.

Code sample showing component inheritance and service injection working together:

import { Component, Injectable } from '@angular/core';

@Injectable()
export class SomeDependency {
  public foo() {
    return 'bar';
  }
}

@Component({
  selector: 'parent-comp',
  template: `<h1>Hello from ParentComponent {{name}}</h1>`,
  providers: [
    SomeDependency
  ]
})
export class ParentComponent { 
  public name;
  constructor(private dep: SomeDependency) {
    this.name = this.dep.foo();
  }
}

@Component({
  selector: 'child-comp',
  template: `<h1>Hello from ChildComponent. SomeDependency returned {{name}}</h1>`,
  providers: [
    SomeDependency
  ]
})
export class ChildComponent extends ParentComponent { 

}


@Component({
  selector: 'my-app',
  template: `<child-comp></child-comp>`
})
export class AppComponent { 

}

See this plunker for a working example: http://embed.plnkr.co/5VNDF6/

I am (also) new to supplying examples in SO, so I might have missed some best practices. Hopefully people will comment on suggestions for improvements.

Of general note, this component inheritance is imho not the best way of doing things - I'd favor composition over inheritance for components. Inheritance - if really required - could be a better fit for services: http://embed.plnkr.co/jWiOTg/