[英]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.