2017-01-23 34 views
3

從Angular v2.0開始,inheritance is supported between components如何繼承從超類注入到Angular 2中的子類組件

給定一個父類,經由依賴注入提供給構造一個服務,是有可能定義哪些延伸(或繼承)它的父類的子類,以使得它可以訪問該父服務

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 

在這個特定情況下,看起來父母注射的服務不是。我想知道:

  1. 這是Angular2的組件繼承支持當前限制?
  2. 此代碼示例中是否存在缺失/錯誤?
  3. 這是Angular2對Component Inheritance支持的錯誤嗎?
+0

爲什麼在組件中使用繼承? – shusson

+0

我誤解了你的問題。這不是父母和孩子,而是子和超級。 –

+0

@Gunter你能澄清嗎?根據我的經驗,父類是子類,因爲超類是子類(當關系樹是2層時)。我錯過了什麼嗎? –

回答

0

讓它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.

+2

可能'受保護'會更好 – shusson

+0

保護也應該工作@shusson –

+0

這不是一個有效的答案。 Typescript的構造函數參數默認爲「public」,所以雖然服務可能更好被「保護」,但上面的示例具有公共服務。 http://www.typescriptlang.org/docs/handbook/classes.html#public-private-and-protected-modifiers –