The*_*inn 5 inheritance dependency-injection typescript angular
从Angular v2.0开始,在components之间支持继承。
给定一个父类,并通过依赖注入为构造函数提供服务,是否可以定义扩展(或继承)其父类的子类,以便其可以访问父类的服务?
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();
}
}
Run Code Online (Sandbox Code Playgroud)
当我们尝试new_child_function()从子类中调用时,它成功访问了其父类的成员foobar,但是对的调用this._my_service.service_function()给我们带来了以下不太有趣的错误:
Cannot read property 'get' of undefined
Run Code Online (Sandbox Code Playgroud)
在这种特定情况下,似乎由父母注入的服务对孩子不可用。我想知道: