2016-05-25 247 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)); 
相关问题