2017-01-23 9 views
3

Angular v2.0の時点で、inheritance is supported between componentsスーパークラスからインジェクションされたサービスを、サブクラス化されたコンポーネントを角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のコンポーネント継承のバグですか?
+0

なぜコンポーネントで継承を使用していますか? – shusson

+0

あなたの質問が間違っています。これは親子ではなく、サブクラスとスーパークラスです。 –

+0

@Gunterあなたは明確にすることができますか?私の経験では、スーパークラスがサブクラス化する(関係ツリーが2深い場合)ため、親は子になります。何か不足していますか? –

答えて

0

あなたがParameter propertiesとそれらがどのように宣言され、アクセスされた詳細を読むことができ、それpublicまたはprotectedすなわち

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 are declared by prefixing a constructor parameter with an accessibility modifier or readonly , or both.

+2

おそらく '保護された'はよりよいかもしれない – shusson

+0

また保護されるべきである@shusson –

+0

これは有効な答えではない。 Typescriptのコンストラクタパラメータはデフォルトで '' public''になっていますので、サービスが '' protected''になる方が良いかもしれませんが、上記の例では公的サービスがあります。 http://www.typescriptlang.org/docs/handbook/classes.html#public-private-and-protected-modifiers –

関連する問題