我无法弄清楚如何将字段绑定到组件,以便在我更改OnDataUpdate()中的属性时更新字段。
字段“OtherValue”具有对输入字段的双向绑定,“Name”字段在显示组件时显示“test”。但是当我刷新数据时,没有任何字段被更新以显示更新的数据。
“this.name”的第一个记录值是未定义的(???),第二个是正确的,但绑定到同一属性的字段不会更新。
组件如何为name-field提供初始值,但是当触发数据更新时,name-property突然未定义?
stuff.component.ts
@Component({
moduleId: __moduleName,
selector: 'stuff',
templateUrl: 'stuff.component.html'
})
export class StuffComponent {
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" />
该 this
如果你像那样传递它就会丢失上下文 subscribe()
功能。您可以通过多种方式解决此问题:
通过使用绑定
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);
}
该 this
如果你像那样传递它就会丢失上下文 subscribe()
功能。您可以通过多种方式解决此问题:
通过使用绑定
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);
}
以这种方式传递方法引用打破了 this
参考
dataservice.subscribe(this.OnDataUpdate);
使用此代替:
dataservice.subscribe((value) => this.OnDataUpdate(value));
通过使用 ()=>
(箭头功能) this
保留并继续引用当前的类实例。
你输了 this
上下文,保持您可以使用的上下文 捆绑。
dataservice.subscribe(this.OnDataUpdate.bind(this));