[英]Angular2 - view not updated after http call
Here is my setup (super simplified): 这是我的设置(超级简化):
template: 模板:
<button (click)="doNothing">Show</button>
<h2>{{count}}</h2>
component: 零件:
count: number;
constructor(private _dataService: DataService) {
this.init();
}
private init(): void {
this._dataService.getAll().subscribe(res=> { //just a simple http GET here
this.count = res;
console.log(this.count); //logs the correct value, but view not updated
});
}
private doNothing(): void { }
As you may have noticed, I'm using a button
that's not doing anything, but unless I click it my view is not updated with the correct value (took me some time to think of this hack). 您可能已经注意到,我使用的
button
什么也不做,但是除非单击该button
,否则我的视图将不会更新为正确的值(花了我一些时间来考虑这种hack)。 What am I actually doing here and how can I replace it with something not so dumb? 我在这里实际上在做什么,如何用不那么笨的东西代替它? All the http samples I found assured me that this should work without any magic, but apparently it doesn't.
我发现的所有http示例都向我保证,这应该没有任何魔力,但显然不是。 I'm using beta6
我正在使用beta6
Simple workaround for this problem can be to use NgZone . 解决此问题的简单方法是使用NgZone 。 NgZone is an injectable service for executing work inside or outside of the Angular zone.
NgZone是用于在Angular区域内或外部执行工作的可注入服务。 So, it can be used to trigger the change detection manually.
因此,它可用于手动触发更改检测。
import {NgZone} from 'angular2/core';
count: number;
private zone: NgZone;
constructor(private _dataService: DataService) {
this.zone = new NgZone({ enableLongStackTrace: false });
this.init();
}
private init(): void {
this._dataService.getAll().subscribe(res=> { //just a simple http GET here
this.zone.run(() => {
this.count = res;
});
});
}
It should indeed work as expected, no magic required, the problem was in my web browser (I was using Chrome Version 48.0.2564.109 m). 它确实应能按预期工作,不需要任何魔术,问题出在我的网络浏览器中(我使用的是Chrome版本48.0.2564.109 m)。 I switched to Edge 20.10240.16384.0 and everything is fine now
我切换到Edge 20.10240.16384.0,现在一切都很好
Are you sure to have included the angular2-polyfills.js file into your main HTML? 您确定已在主要HTML中包含angular2-polyfills.js文件吗? This file contains ZoneJS that is responsible from triggering view updates.
该文件包含ZoneJS,负责触发视图更新。
I had a similiar problem and using the workaround provided by @SaUrAbH MaUrYa it worked. 我有一个类似的问题,使用@SaUrAbH MaUrYa提供的解决方法可以正常工作。 But I was not satified with this, so searching more I found another way, that seems better:
但是我对此并不满意,因此在搜索更多内容时,我发现了另一种方法,那就更好了:
ngOnInit() {
this._dataService.getAll().subscribe(res=> this.count = res);}
For me, It works. 对我来说,它有效。 I hope it works for you either
我希望它对你有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.