angular - 如何将注入(inject)服务从父类(super class)继承到 Angular 2 中的子类组件

标签 angular inheritance typescript dependency-injection

从 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)服务对子可用。我想知道:

  1. 这是 Angular2 的组件继承支持的当前已知限制吗?
  2. 此代码示例是否有遗漏/错误?
  3. 这是 Angular2 对组件继承的支持的错误吗?

最佳答案

将其设置为publicprotected,即

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.

关于angular - 如何将注入(inject)服务从父类(super class)继承到 Angular 2 中的子类组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41817759/

相关文章:

javascript - 如何将 md-input 绑定(bind)到 md-slider 值 angular2

javascript - TypeScript 平面数组到对象树

php - 在 PHP 中从父类调用子方法

Java继承(抱歉我不知道如何在标题中说清楚......)

javascript - 将时刻格式化为字符串

angular - 部署 angular 8 和 asp.net core 3.1 的步骤

javascript - 为什么我的 ng-template 和 ngIf 中的代码无法正常工作

c++ - 可以在 C++ 中使用 dynamic_cast 进行向上转换和向下转换

typescript - 不一致隐式有 'any' 类型错误

google-app-engine - 我应该如何在我的 Angular 2 项目中包含外部 .js 文件?