[英]Angular2 Update View on async model update
我有一個依賴於數據存儲的Angular2組件。 模板在該存儲上具有一些數據綁定,例如“ {{datastore.weather.curTemp}}”。數據存儲會通過http進行不時更新。
現在,我知道這可以以一種非常規的方式工作-這就是當新數據到達時,我的curTemp不會自動更新的原因,對嗎?
我當前的解決方案是使用EventEmitter通知組件有關更改,但是如果我需要從數據存儲中獲取大量變量,則需要綁定到本地變量,否則可能會造成混亂,或者我將調用detectChanges ()在ChangeDetectorRef。
我在正確的軌道上嗎? 還是我缺少一種簡單的填充asny數據的方法?
謝謝!
解決您的問題的一種方法是使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}}
這樣,當組件被銷毀時,您也不需要處理訂閱,因為異步管道會為您執行訂閱。
如果您的組件未更新,則您的異步線程可能正在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;
});
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.