Angular2模板不更新

时间:2017-06-12 20:20:48

标签: angular typescript electron

我在3秒后更新了组件的消息,但它没有在模板中更新。我尝试过安装angular2-polyfills(有些人说尝试过),我已经尝试了

constructor(private cd: ChangeDetectorRef)
{ ....
    this.cd.markForCheck();
  ....
}

但似乎没有任何效果。这是完整的组件:

import { Component, ViewEncapsulation, ChangeDetectorRef } from 
'@angular/core';

//Defines a standard component
@Component({
  selector: 'app',
  templateUrl: './App.component.html'
})
export class AppComponent {
message: String = "hello"; //Message im trying to update

 //Just to try ChangeDetectorRef...
 constructor(private cd: ChangeDetectorRef)
 {
    //Timer that sets the message to '"HELLOWITHOUTWORLD" after 3 seconds
    window.setTimeout(function () { 
        this.message = "HELLOWITHOUTWORLD"; 
        console.log("changed it " + this.message); 
    }, 3000);
    //I ALSO TRIED DOING "this.zone.run" but kept getting zone is undefined
    //window.setTimeout(function () { this.zone.run(() => { this.message = "HELLOWITHOUTWORLD"; console.log("changed it"); }); }, 3000);

    //Some sites said that this would update the template...
    this.cd.markForCheck();
 }
}

和HTML:

{{message}}

1 个答案:

答案 0 :(得分:1)

我在这里找到了类似的问题:Angular 2, how to use setTimeout?

在一个简单的plnkr中尝试了它,解决方法是将function() { /* ... */ }更改为箭头函数() => { /* ... */ }。这些箭头函数将正确设置块的上下文。

您的问题是this内的function()是一个孤立的范围而不是您所期望的课程。对于变化检测,与angularjs相比,angular2及更高版本非常直观:它不再适用于摘要周期,并且很少需要您的输入。

如果您有以前的JS经验,可以将() => {}想象为

var _this = this;
function () {
  var this = _this;
  /* code */
}