从 Angular v2.0 开始,inheritance is supported between components .
给定一个父类,通过依赖注入(inject)向构造函数提供服务,是否可以定义一个子类扩展(或继承)它的父类,这样它就可以访问 parent 的服务?
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();
}
}
当我们尝试从子类调用 new_child_function()
时,它成功访问了其父类的成员 foobar,但是对 this._my_service.service_function 的调用()
给了我们以下不太有趣的错误:
Cannot read property 'get' of undefined
在这种特定情况下,似乎父注入(inject)服务不对子可用。我想知道:
- 这是 Angular2 的组件继承支持的当前已知限制吗?
- 此代码示例是否有遗漏/错误?
- 这是 Angular2 对组件继承的支持的错误吗?
最佳答案
将其设置为public
或protected
,即
constructor(protected _my_service: MyService){};
if you do not use in the constructor
protected
,private
, orpublic
, for example, DI, the range of the variable_my_service
is the scope of theconstructor { }
you could not use from another function.
您可以阅读更多关于 Parameter properties 的信息以及如何声明和访问它们。
Parameter properties are declared by prefixing a constructor parameter with an accessibility modifier or
readonly
, or both.
关于angular - 如何将注入(inject)服务从父类(super class)继承到 Angular 2 中的子类组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41817759/