angular 2 injection not work in inheritance

余生颓废 提交于 2019-12-31 05:22:08

问题


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/



来源:https://stackoverflow.com/questions/41789601/angular-2-injection-not-work-in-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!