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

新手上路,请多包涵

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

字段“OtherValue”具有绑定到输入字段的两种工作方式,“名称”字段在显示组件时显示“测试”。但是当我刷新数据时,没有任何字段被更新以显示更新后的数据。

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

怎么组件给name-field提供初始值,触发数据更新时,name-property突然undefined?

东西.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);
}

东西.component.html

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

原文由 Kristoffer Berge 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 492
2 个回答

如果您像在 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);
}

原文由 Poul Kruijt 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

dataservice.subscribe(this.OnDataUpdate);

改用这个:

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

通过使用 ()=> (箭头函数) this 被保留并继续引用当前类实例。

原文由 Günter Zöchbauer 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题