问题 当Angular2中的属性更改时,数据绑定不会更新


我无法弄清楚如何将字段绑定到组件,以便在我更改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" />

6798
2018-05-25 13:37


起源



答案:


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);
}

11
2018-05-25 13:41



如果它不是函数调用并且是值赋值怎么办? @pierreduc - Amirhosein Al
然后,您应该将该分配包装在匿名箭头函数中 - PierreDuc


答案:


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);
}

11
2018-05-25 13:41



如果它不是函数调用并且是值赋值怎么办? @pierreduc - Amirhosein Al
然后,您应该将该分配包装在匿名箭头函数中 - PierreDuc


以这种方式传递方法引用打破了 this 参考

dataservice.subscribe(this.OnDataUpdate);

使用此代替:

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

通过使用 ()=> (箭头功能)  this 保留并继续引用当前的类实例。


2
2018-05-25 13:40





你输了 this 上下文,保持您可以使用的上下文 捆绑

dataservice.subscribe(this.OnDataUpdate.bind(this));

0
2018-01-05 11:53