截至Angular v2.0,inheritance is supported between 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(); } }
当我们尝试从子类调用new_child_function()时,它会成功访问其父成员foobar,但是对this._my_service.service_function()的调用会给我们带来以下不那么有趣的错误:
Cannot read property 'get' of undefined
在这种特定情况下,孩子看不到父母注射的服务.我想知道:
>这是Angular2的组件继承支持的当前已知限制吗?
>此代码示例是否缺少/错误?
>这是Angular2对组件继承的支持的错误吗?
解决方法
公开或保护,即
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.