2016-05-25 148 views
7

我找不出如何將字段綁定到組件,以便在更改OnDataUpdate()中的屬性時字段會更新。當Angular2屬性發生更改時,數據綁定不會更新

字段「OtherValue」具有綁定到輸入字段的雙向工作方式,「Name」字段顯示組件時顯示「test」。但是,當我刷新數據,沒有任何字段更新顯示更新的數據。

「this.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

<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(this.OnDataUpdate.bind(this)); 
} 

通過使用匿名箭頭函數包裝

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

變化的函數的聲明

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

傳遞方法引用這樣打破了this參考

dataservice.subscribe(this.OnDataUpdate); 

用這個代替:

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

通過使用()=> (arrow function)this被保留並繼續引用當前類實例。

0

您正在失去this上下文,以保持上下文,您可以使用bind

dataservice.subscribe(this.OnDataUpdate.bind(this)); 
相關問題