2017-06-12 120 views
1

我在3秒後更新組件的消息,但它不在模板中更新。我試着安裝angular2-polyfills(有些人說是嘗試),我試過Angular2模板不更新

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

我發現了一個類似的問題在這裏:Angular 2, how to use setTimeout?

嘗試過了一個簡單的plnkr解決的辦法是改變function() { /* ... */ }到箭頭功能() => { /* ... */ }。這些箭頭函數將正確設置塊的上下文。

您的問題是function()中的this是一個隔離的範圍,而不是您所期望的那樣。對於更改檢測,與angularjs相比,angular2及以上版本非常直觀:它不再適用於摘要循環,並且很少需要您的輸入。

如果有JS之前的經驗,你能想象() => {}作爲

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