How to inherit an embedded service from a superclass to a subclass component in Angular 2

Starting with Angular v2.0, inheritance is supported between components .

Given the parent class that provides the constructor through dependency injection, is it possible to define a child class that extends (or inherits) its parent class so that it can access the parent 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 to call new_child_function()from a child class, it successfully calls its parent member foobar , but the call this._my_service.service_function()gives us the following error not so much fun:

Cannot read property 'get' of undefined

It seems that in this particular case, parental injection is not available to the child. I am wondering:

  • Angular2 ?
  • - / ?
  • Angular2 ?
+4
1

public protected, ..

constructor(protected _my_service: MyService){};

protected, private public, , DI, _my_service constructor { }, .


, .

readonly .

+1

Source: https://habr.com/ru/post/1667594/


All Articles