2017-06-12 15 views
1

コンポーネントのメッセージは3秒後に更新されますが、テンプレートでは更新されません。私はAngular2テンプレートが更新されない

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

を試してみたが、何も動いていないようにみえ、(一部の人々はそれをしようとすると)angular2-polyfillsをインストールしようとしました。ここでは、完全なコンポーネントがあります:

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は、あなたが期待していたクラスではなく、隔離されたスコープであることでした。変化検出のためには、angular2と比較すると、angular2以上は直感的です。ダイジェストサイクルではうまく機能せず、ほとんど入力を必要としません。あなたが前にJSの経験をお持ちの場合は

あなたが想像できる() => {}

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

として
関連する問題