Mam obiekt, który zawiera pole bar: foo.bar. Jest ono wyświetlane w widoku
0
0
Pokaż coś kodu, bo powinno działać.
0
Plik .ts:
ngAfterViewInit() { // w ngOnInit, też nie działa
this.service.getData()
.subscribe(data => {
this.fun(data);
},
error => console.log('Error')
);
}
private fun(data) {
let totalCount = 0;
let totalSum = 0;
...
if (totalCount > 0) {
this.foo.bar = totalSum / totalCount;
}
console.log(this.foo.bar); // poprawnie wyświetla wartość
}
Widok:
{{foo.bar}} |
0
this.foo
to cały czas ten sam obiekt, zmieniasz tylko jego właściwość. Angular używa operatora ===
, gdy robi dirty checking. Co z tego wynika?
const foo = { name: 'John' };
const bar = foo;
console.log(foo === bar); // true
bar.name = 'Bob';
console.log(foo === bar); // true
Dla Angulara this.foo
się nie zmienia do momentu, aż nie zrobisz tak:
this.foo = { bar: ... }
Możesz użyć ngDoCheck lub zrobić tak:
private fun(data) {
let totalCount = 0;
let totalSum = 0;
...
if (totalCount > 0) {
this.foo = {
...this.foo,
bar: totalSum / totalCount
}
}
}