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

时间:2016-05-25 13:37:50

标签: 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);
}

stuff.component.html

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

3 个答案:

答案 0 :(得分:12)

如果您在this函数中传递subscribe()上下文,则会丢失constructor(private dataservice: DataSeriesService) { dataservice.subscribe(this.OnDataUpdate.bind(this)); } 上下文。您可以通过以下几种方式解决此问题:

使用bind

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

更改函数声明

var data = [{a:a}, {a:b}, {a:c}];
var webview = Titanium.UI.createWebView({url:'my_template.html'});
var str = "Hello world!";
webview.evalJS("generateTable('"data"');");

答案 1 :(得分:2)

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

dataservice.subscribe(this.OnDataUpdate);

改为使用:

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

保留使用()=> (arrow function) this并继续引用当前的类实例。

答案 2 :(得分:0)

您正在丢失dataservice.subscribe(this.OnDataUpdate.bind(this)); 上下文,以保留您可以使用的上下文bind

{{1}}