如何在Angular 2中将Injected服务从超类继承到子类组件
截至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的组件继承支持的当前已知限制吗? 解决方法
公开或保护,即
constructor(protected _my_service: MyService){};
您可以阅读有关Parameter properties以及如何声明和访问它们的更多信息.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |