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

Kri*_*rge 14 html typescript angular

我无法弄清楚如何将字段绑定到组件,以便在我更改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);
}
Run Code Online (Sandbox Code Playgroud)

stuff.component.html

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

Pie*_*Duc 13

this如果你传递这样的背景下,失去subscribe()功能.您可以通过多种方式解决此问题:

通过使用绑定

constructor(private dataservice: DataSeriesService) {
    dataservice.subscribe(this.OnDataUpdate.bind(this));
}
Run Code Online (Sandbox Code Playgroud)

通过使用匿名箭头函数包装器

constructor(private dataservice: DataSeriesService) {
    dataservice.subscribe((data : any) => {
        this.OnDataUpdate(data);
    });
}
Run Code Online (Sandbox Code Playgroud)

更改功能的声明

OnDataUpdate = (data: any) : void => {
      console.log(this.Name);
      this.Name = data.name;
      this.OtherValue = data.otherValue;
      console.log(this.Name);
}
Run Code Online (Sandbox Code Playgroud)