Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Html Angular2中的属性更改时数据绑定不更新_Html_Typescript_Angular - Fatal编程技术网

Html Angular2中的属性更改时数据绑定不更新

Html Angular2中的属性更改时数据绑定不更新,html,typescript,angular,Html,Typescript,Angular,我不知道如何将字段绑定到组件,以便在我更改OnDataUpdate()中的属性时更新字段 字段“OtherValue”与输入字段具有双向工作绑定,“Name”字段在显示组件时显示“test”。但是当我刷新数据时,没有一个字段被更新以显示更新的数据 “this.name”的第一个记录值未定义(?),第二个记录值正确,但绑定到同一属性的字段不会更新 组件如何为name字段提供初始值,但当触发数据更新时,name属性突然未定义 stuff.component.ts @组件({ moduleId:uu

我不知道如何将字段绑定到组件,以便在我更改OnDataUpdate()中的属性时更新字段

字段“OtherValue”与输入字段具有双向工作绑定,“Name”字段在显示组件时显示“test”。但是当我刷新数据时,没有一个字段被更新以显示更新的数据

“this.name”的第一个记录值未定义(?),第二个记录值正确,但绑定到同一属性的字段不会更新

组件如何为name字段提供初始值,但当触发数据更新时,name属性突然未定义

stuff.component.ts

@组件({
moduleId:uu moduleName,
选择器:“东西”,
templateUrl:'stuff.component.html'
})
导出类组件{
名称:string=“test”;
其他值:字符串;
构造函数(专用数据服务:DataSeriesService){
订阅(this.OnDataUpdate);
}
OnDataUpdate(数据:任意){
console.log(this.Name);
this.Name=data.Name;
this.OtherValue=data.OtherValue;
console.log(this.Name);
}
stuff.component.html


名称
{{Name}}
其他
{{OtherValue}}

以这种方式传递方法引用会破坏
引用

dataservice.subscribe(this.OnDataUpdate);
改用这个:

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

通过使用
可以保留此
并继续引用当前类实例。

如果在
subscribe()
函数中像这样传递它,则会丢失
上下文。可以通过以下几种方式修复此问题:

通过使用bind

通过使用匿名arrow函数包装器

更改函数的声明


您正在丢失
上下文,以保留您可以使用的上下文


如果它不是一个函数调用,而是一个值赋值呢???@pierreduch您应该将该赋值包装在一个匿名箭头函数中
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);
}
dataservice.subscribe(this.OnDataUpdate.bind(this));