2017-09-16 8 views
1

この基本的なapp.component.tsサンプルスニペット(学習目的でのみ作成されています)では、コンストラクタでsetIntervalブロックを使用すると、テンプレート変数を文字列で補間してそのブロックは機能しません。文字列補間がsetIntervalから機能しない

これは意味のある例ではありませんが、問題を示しています:
テンプレートの{{timeDisplay}}領域を更新するにはどのようなテクニックを使用する必要がありますか?

これは範囲の問題のようです。 これはグローバル変数を介して解決できますか?または、この機能に取り組むためのよりよい方法は何ですか?

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

export class Hero { 
    id: number; 
    name: string; 
} 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 

    timeDisplay: string; 

    constructor() { 
    this.timeDisplay = 'time will be displayed right here.'; 

    // set timer 
    setInterval(
     function(){ 
      this.timeDisplay = new Date(); // this does not create an error but does not do anything neither. it is most likely timeDisplay variable is not in the constructor's scope 
     }, 
     1000 
    ); 

    } 

答えて

1

問題は、関数式は、コンテキストを保持していないので、あなたはここにthisのためのコンテキストを失っているということです。

// set timer 
setInterval(
    function(){ 
     this.timeDisplay = new Date(); // this does not create an error but does not do anything neither. it is most likely timeDisplay variable is not in the constructor's scope 
     ^^^ - points to global object, not `AppComponent` 
    }, 
    1000 
); 

変更、それはコンテキストを維持する機能を矢印:

// set timer 
setInterval(
    () => { 
     this.timeDisplay = new Date(); 
    }, 
    1000 
); 

詳細については、this answerを参照してください。

+0

あなたは正しいです。それは私が探していた答えですが、私はまだあなたのアプローチがなぜ機能するのか理解できません。作業コードをもう少し詳しく説明できますか?あなたは矢印の機能を使っているのです。それですか? –

+0

@AverageJoe、もう少し説明を追加しました。はい、矢印関数は 'this'のコンテキストを保持します。これは必須です。私がリンクした答えは、あなたがなぜそれが動作するのかを理解するために必要なすべての情報を提供します。 –

+0

コードにもう1つ問題があります。私は、オブジェクト(日付オブジェクト)を文字列に割り当てました。その結果、現在のコードから有効な実行時間が得られません。 AngularではPHPのように一時的な型変換が行われていますか?ex:(int) '5'。新しいDateレスポンスの文字列表現を(アラートに表示されるように)割り当てるにはどうすればよいですか?アラート(新しい日付())が機能します。 –