Angular 异步函数不更新视图
自从升级到Angular 9后,我遇到了一些问题。例如,以下代码过去对我来说运行良好:Angular 异步函数不更新视图,angular,angular2-changedetection,Angular,Angular2 Changedetection,自从升级到Angular 9后,我遇到了一些问题。例如,以下代码过去对我来说运行良好: this.countdownSubscription = interval(1000).subscribe(() => { this.recentAuctions.forEach(a => { a.timeLeft = this.auctionService.getTimeLeft(a); }); }); 因此,在这个订阅中,我正在更改拍卖对象上的timeLeft。在我显示的HT
this.countdownSubscription = interval(1000).subscribe(() => {
this.recentAuctions.forEach(a => {
a.timeLeft = this.auctionService.getTimeLeft(a);
});
});
因此,在这个订阅中,我正在更改拍卖
对象上的timeLeft
。在我显示的HTML中。但是,除非我在ChangeDetectorRef
实例上调用detectChanges()
,否则更改不会反映在视图中
这是预期的行为吗?在异步函数中更改视图后,是否应该调用
detectChanges()
?如果不是,问题是什么?感谢您的帮助。谢谢。使用NgZone
在Run
函数中运行您的函数:
import { NgZone } from '@angular/core';
constructor(private zone: NgZone) {}
MyFunction() {
this.countdownSubscription = interval(1000).subscribe(() => {
this.zone.run(() => this.recentAuctions.forEach(a => a.timeLeft = this.auctionService.getTimeLeft(a)));
});
}
这将更新您的视图。
更多关于NgZone的信息:这个问题在Angular 9中出现的方式很奇怪,但之前没有问题 我唯一的想法是尝试不可变地更新
a
对象和recentations
数组,这样它们就可以获得指向它们在内存中的位置的新指针,并有望启动更改检测
尝试:
看看这是否有效。.map
将对象数组转换为内存中的新位置,spread操作符…auction
将对象的先前键/值分散到内存中的新位置,但timeLeft
将被覆盖
this.countdownSubscription = interval(1000).subscribe(() => {
this.recentAuctions = this.recentAuctions.map(auction => ({
...auction,
timeLeft: this.auctionService.getTimeLeft(auction),
}));
});