加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何在Angular 2中将Injected服务从超类继承到子类组件

发布时间:2020-12-17 17:08:59 所属栏目:安全 来源:网络整理
导读:截至Angular v2.0,inheritance is supported between components. 给定父类,通过依赖注入向构造函数提供服务,是否可以定义扩展(或继承)其父类的子类,以便它可以访问父服务? import {MyService} from './my.service'import {OnInit} from '@angular/core'@Co
截至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,or public,for example,DI,the range of the variable _my_service is the scope of the constructor { } 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读