Reputation: 706
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). 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. I'm using beta6
Upvotes: 1
Views: 364
Reputation: 303
I had a similiar problem and using the workaround provided by @SaUrAbH MaUrYa it worked. 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
Upvotes: 0
Reputation: 202346
Are you sure to have included the angular2-polyfills.js file into your main HTML? This file contains ZoneJS that is responsible from triggering view updates.
Upvotes: 0
Reputation: 706
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). I switched to Edge 20.10240.16384.0 and everything is fine now
Upvotes: 1
Reputation: 1638
Simple workaround for this problem can be to use NgZone. NgZone is an injectable service for executing work inside or outside of the Angular zone. 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;
});
});
}
Upvotes: 3