angular 2 injection not work in inheritance

前端 未结 1 1368
后悔当初
后悔当初 2021-01-26 10:34

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\
1条回答
  •  礼貌的吻别
    2021-01-26 11:17

    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: `

    Hello from ParentComponent {{name}}

    `, providers: [ SomeDependency ] }) export class ParentComponent { public name; constructor(private dep: SomeDependency) { this.name = this.dep.foo(); } } @Component({ selector: 'child-comp', template: `

    Hello from ChildComponent. SomeDependency returned {{name}}

    `, providers: [ SomeDependency ] }) export class ChildComponent extends ParentComponent { } @Component({ selector: 'my-app', template: `` }) 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/

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