2016-05-24 61 views
1

我有一個簡單的角度模型2.我有函數,每秒執行html.get,但放置在視圖中的變量不刷新自己。問題是什麼 ?Angular2 http.get在間隔1s不刷新視圖

constructor(private _cm: Communication) {} 

ngOnInit() { 
    setInterval(() => { 
     this.getDeviceData(); 
     this.numCountChange.next(this.responseDate) 
    }, 1000); 
} 

ngOnDestroy() { 
    clearInterval(this.requestInterval); 
} 

getDeviceData() { 
    this._cm.devicesService.getAccessPointStateByIdDeviceAndIdAccessPoint(10018, 10154) 
      .subscribe(
       accessPoint => { 
        this.device0 = accessPoint; 
        this.device0.stateChecker(); 
        this.responseDate = new Date() 
        console.log(this.responseDate); 
       }, 
       error => console.log(error) 
      ); 
} 

HTML:

    < div class="small-box-footer"> 
         {{ responseDate }} 
        < /div> 

responseDate顯示所有的時間,第一響應值

回答

1

應該無需手動調用變化檢測工作,但我不知道是什麼,例如devicesService.getAccessPointStateByIdDeviceAndIdAccessPoint究竟是幹什麼以及代碼的樣子。

這至少應該解決它:

constructor(private _cm: Communication, private cdRef:ChangeDetectorRef) {} 

ngOnInit() { 
    setInterval(() => { 
     this.getDeviceData(); 
     this.numCountChange.next(this.responseDate) 
    }, 1000); 
} 

ngOnDestroy() { 
    clearInterval(this.requestInterval); 
} 

getDeviceData() { 
    this._cm.devicesService.getAccessPointStateByIdDeviceAndIdAccessPoint(10018, 10154) 
      .subscribe(
       accessPoint => { 
        this.device0 = accessPoint; 
        this.device0.stateChecker(); 
        this.responseDate = new Date() 
        console.log(this.responseDate); 
        this.cdRef.detectChanges() 
       }, 
       error => console.log(error) 
      ); 
} 
+0

此解決方案,但是,當我得到的鏈接來查看發生了另一個錯誤 EXCEPTION:試圖使用一個被毀壞的觀點:detectChanges – Emerceen

+0

那是一個棘手的例外。你可以請嘗試將'subscribe'的返回值存儲到類屬性(例如'subscription'),如'this.subscription = this._cm.deviceService.getAccessPoint ... subscribe()'和'ngOnDestroy()調用'this.subscription.unsubscribe()'? –