How to inherit Injected service from superclass into subclassed component in Angular 2

Discussão em 'Angular' iniciado por The Aelfinn, Novembro 29, 2024.

  1. The Aelfinn

    The Aelfinn Guest

    As of Angular v2.0, inheritance is supported between components.

    Given a parent class, with a service provided to the constructor via dependency-injection, is it possible to define a child class which extends (or inherits) its parent class, such that it can access the parent's service?

    import {MyService} from './my.service'
    import {OnInit} from '@angular/core'

    @Component({
    selector: 'parent-selector',
    providers: [MyService],
    templateUrl: 'my_template.html'
    })
    export class ParentClass implements OnInit{
    public foobar: number;
    constructor(protected _my_service: MyService){};

    ngOnInit(){
    foobar = 101;
    }
    }

    @Component({
    selector: 'child-selector',
    templateUrl: 'my_template.html'
    })
    export class ChildClass extends ParentClass{
    public new_child_function(){
    // This prints successfully
    console.log(this.foobar);
    // This throws an error saying my_service is "undefined"
    this._my_service.service_function();
    }
    }


    When we try and call new_child_function() from the child class, it succesfully accesses its parent member foobar, but the call to this._my_service.service_function() gives us the following not-so-fun error:


    Cannot read property 'get' of undefined
    ​

    It appears the parent-injected service is not available to the child in this specific case. I am wondering:

    1. Is this a current known limitation of Angular2's Component Inheritance support?
    2. Is there something missing/wrong with this code sample?
    3. Is this a bug with Angular2's support for Component Inheritance?

    Continue reading...

Compartilhe esta Página