我遇到了变化检测的问题,我无法弄清楚什么是错误的,或者我只是不理解Angular。我查看了类似问题的stackoverflow答案,但方法没有解决我的问题。
我有一个服务,存储一些情感,我有2个模态组件订阅。我有一个用户选择情绪的模态,然后模态使用服务来更新选定的情绪。第二个模态还订阅所选择的情绪,并在收到更新时更新其类别上的情绪列表。我尝试了几种方法,如detectChanges()和tick()无济于事。我知道订阅正在运行,模式正在接收更新的情绪列表,但不知何故,更改检测根本不起作用,并且未触发视图更新。我无法弄清楚为什么手动触发变化检测不起作用,这让我质疑我的理解。我想如果我在类中更新了this.emotions,视图依赖于它,那将触发更新....
服务:
@Injectable()
export class BeforeFormProvider {
selectedEmotions = new BehaviorSubject({});
selectedDistractions = new BehaviorSubject({});
constructor(private databaseProvider: DatabaseProvider) {
}
updateEmotions(emotions) {
this.selectedEmotions.next(emotions);
}
updateDistractions(distractions) {
this.selectedDistractions.next(distractions);
}
}
变更检测不起作用的模态:我只会包含具有更新逻辑的类的一部分。我有作为班级财产的情感。
ngOnInit() {
//automatically generate date/time to current for form
this.date = this.datePipe.transform(new Date(), 'mediumDate');
this.time = this.datePipe.transform(new Date(), 'shortTime');
this.emotionsSubscription = this.bfProvider.selectedEmotions.subscribe(emotions => {
this.emotions = emotions;
this.ref.tick();
});
this.distractionsSubscription = this.bfProvider.selectedDistractions.subscribe(distractions => this.distractions = distractions);
}
模态HTML:p标签没有更新,它永远不会识别任何变化!我无法弄清楚我做错了什么。
<ion-item detail-push (click)="openEmotionsList()">
<h2>Emotions</h2>
<p>{{emotions | getValues}}</p>
</ion-item>
我想通了。在通过服务中的.next()发送之前,我需要创建列表的新副本。我正在保存对Modals中通过subscribe返回的对象的引用,然后在服务的每次更新时发回相同对象的变异版本,因此它不会触发视图更新。
updateEmotions(emotions) {
this.selectedEmotions.next({...emotions});
}
而不是制作副本,请查看您的getValues管道,确保它未设置为纯:
@Pipe({
name: 'getValues',
pure: false
})