2016-08-20 64 views
0

我有一個依賴於數據存儲的Angular2組件。 模板在該商店有一些數據綁定,例如「{{datastore.weather.curTemp}}」 Datastore get通過http不時更新。Angular2更新異步模型更新視圖

現在我明白這是以asnyc方式工作 - 這是我的curTemp在新數據到達時不會自動更新的原因,對嗎?

我目前的解決方案是使用EventEmitter來通知我的組件發生了變化,但是我需要一個局部變量綁定到,如果我需要來自我的數據存儲區的大量變量,我會在ChangeDetectorRef上調用detectChanges()。

我在正確的軌道上嗎?或者我錯過了填充我的asny-data的簡單方法?

謝謝!

+0

你嘗試過異步管https://angular.io/docs/ts/latest/guide/pipes.html – rdRahul

+0

,這將意味着簡單地揭露我的變量觀測量,對不對?聽起來很有前途,謝謝你! - 更新:嘗試過,但它並沒有更新我的觀點:( –

回答

0

爲您解決問題的一種方法是使weather一個Subject

datastore.service.ts

public weather: Subject<any> = new Subject(); // better make this private and expose it `asObservable` via a getter nethod 

updateWeather(){ 
    http.get(...).subscribe(res => this.weather.next(res.json())) 
} 

然後,您可以在您的component.ts得到一個參考:

public weather$: Observable<any>; 
constructor (dataStore: DataStore){ 
    this.weather$ = dataStore.weather; 
} 

並將其用於您的模板中,如下所示:

{{(weather$ | async).curTemp}} 

通過這種方式,當異步管道爲您完成組件銷燬時,您也不需要處理訂閱。

+0

謝謝..我已經嘗試過,但它不會更新以及... –

+0

這真的很奇怪:如果我不斷重新加載我的網頁,每隔x次綁定工作的意圖..剩下的時間它不會得到更新....? –

+0

我的錯誤是由於一些非常奇怪的東西......見:http://stackoverflow.com/questions/39057644/angular2-當-使用視圖未更新完畢-的setInterval?noredirect = 1#comment65467196_39057644 –

0

如果你的組件沒有更新,也許你的異步線程運行在NgZone之外,你可能需要通過在組件的NgZone內進行分配來更新組件。

import {Component, NgZone} from "@angular/core"; 

@Component({ 
    selector: 'app', 
    templateUrl: './app.component.html' 
}) 

export class MyComponent { 
    myValue: string; 

    constructor(private ngZone: NgZone) { 
    } 

    getData() { 
    const self = this; 
    myAsyncCall().then(result => { 
     ngZone.run(() => { 
     self.myValue = result; 
     }); 
    }); 
    } 
}