2016-05-25 26 views
7

OnDataUpdate()のプロパティを変更するとフィールドが更新されるように、フィールドをコンポーネントにバインドする方法がわかりません。プロパティがAngular2で変更されたときにデータバインディングが更新されない

"OtherValue"フィールドは、入力フィールドに有効な双方向バインディングを持ち、 "Name"フィールドは、コンポーネントが表示されたときに "test"を表示します。しかし、データを更新すると、更新されたデータを表示するためにフィールドが更新されません。

"this.name"の最初に記録された値は未定義(???)で、2番目は正しいものの、同じプロパティにバインドされたフィールドは更新されません。

コンポーネントはどのようにして名前フィールドの初期値を提供できますか?データ更新がトリガーされると、nameプロパティが突然定義されません。

stuff.component.ts

@Component({ 
    moduleId: __moduleName, 
    selector: 'stuff', 
    templateUrl: 'stuff.component.html' 
}) 

export class BuildingInfoComponent { 
    Name: string = "test"; 
    OtherValue: string; 

    constructor(private dataservice: DataSeriesService) { 
     dataservice.subscribe(this.OnDataUpdate); 
    } 

    OnDataUpdate(data: any) { 
     console.log(this.Name); 
     this.Name = data.name; 
     this.OtherValue = data.otherValue; 
     console.log(this.Name); 
} 

stuff.component.htmlこの方法は、この代わりにthis参照

dataservice.subscribe(this.OnDataUpdate); 

使用を破る方法参照を渡す

<table> 
    <tr> 
     <th>Name</th> 
     <td>{{Name}}</td> 
    </tr> 
    <tr> 
     <th>Other</th> 
     <td>{{OtherValue}}</td> 
    </tr> 
</table> 
<input [(ngModel)]="OtherValue" /> 

答えて

7

subscribe()関数のように渡すと、thisコンテキストが失われます。あなたはいくつかの方法でこの問題を解決することができ:匿名矢印関数ラッパー

constructor(private dataservice: DataSeriesService) { 
    dataservice.subscribe((data : any) => { 
     this.OnDataUpdate(data); 
    }); 
} 

変更関数の宣言を使用してバインド

constructor(private dataservice: DataSeriesService) { 
    dataservice.subscribe(this.OnDataUpdate.bind(this)); 
} 

を使用して

OnDataUpdate = (data: any) : void => { 
     console.log(this.Name); 
     this.Name = data.name; 
     this.OtherValue = data.otherValue; 
     console.log(this.Name); 
} 
+0

これは、関数呼び出しではなく、値の代入ですか? @pierreduc –

+0

次に、その割り当てを無名矢印関数で囲む必要があります – PierreDuc

2

dataservice.subscribe((value) => this.OnDataUpdate(value)); 

を使用すると、()=> (arrow function)thisが保持され、現在のクラスインスタンスを参照し続けます。

0

thisコンテキストが失われているため、使用できるコンテキストを保持しますbind

dataservice.subscribe(this.OnDataUpdate.bind(this)); 
関連する問題