2017-09-16 15 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

代碼中還有一個問題;我碰巧將一個對象(即日期對象)分配到一個字符串上。因此,我們沒有獲得當前代碼的有效運行時間。在Angular中,是否有像PHP一樣的臨時類型轉換:ex:(int)'5'。我們可以做些什麼來分配新日期響應的字符串表示形式(例如它將顯示在警報中)?警報(新日期())起作用。 –