【发布时间】:2018-12-18 17:03:36
【问题描述】:
当我从带有组件 1 的模块切换到带有组件 2 的模块时,我收到以下错误:
错误错误:ExpressionChangedAfterItHasBeenCheckedError:表达式 检查后有变化。以前的值:'ngIf: [object 目的]'。当前值:'ngIf: [object Object],[object 对象],[对象对象],[对象对象],[对象对象],[对象 对象],[对象对象],[对象对象],[对象对象]'
两个模块都使用
ChangeDetectionStrategy.OnPush
当我自己订阅时,一切都很好:
this.bookings$.pipe(takeUntil(this._destroy$)).subscribe(res => console.log(res));
但只要我使用异步管道进行订阅,更改检测就会中断:
<ion-list *ngIf="bookings$ | async as bookings; else loading">
</ion-list>
模块/组件 2 的 init 在更改路由时比组件 1 的销毁更快。因此,组件 1 在销毁之前获取由组件 2 日期更改发起的更改(filteredBookings)。但这应该不是问题?
服务:
constructor(
private afs: AngularFirestore
) {
this.bookingsCollection = afs.collection<Booking>('bookings');
this.bookingsCollection
.snapshotChanges()
.pipe(
takeUntil(this._destroy$),
map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as Booking;
const id = a.payload.doc.id;
return {id, ...data};
});
})
)
.subscribe((bookings: Booking[]) => {
this._bookings.next([...bookings]);
this.refreshFilteredBookings();
});
this.bookings$ = this._bookings
.asObservable()
.pipe(
filter(bookings => bookings !== null)
);
this.filteredBookings$ = this._filteredBookings
.asObservable()
.pipe(
filter(bookings => bookings !== null),
);
}
private refreshFilteredBookings(): void {
const bookings: Booking[] = JSON.parse(JSON.stringify(this._bookings.value));
const filteredBookings: Booking[] = bookings.filter(booking =>
moment(booking.date).isBetween(this.minDate, this.maxDate, null, '[]')
);
this._filteredBookings.next(filteredBookings);
}
setDate(date: Moment, type: string) {
this.minDate = date.startOf(type as unitOfTime.StartOf).format();
this.maxDate = date.endOf(type as unitOfTime.StartOf).format();
if (this._bookings.value) {
this.refreshFilteredBookings();
}
}
组件 1:
ngOnInit() {
this.bookings$ = this._bookingService.filteredBookings$;
}
组件 2:
ngOnInit() {
this.view = 'month';
this.date = moment().format();
this.onDateChange();
}
onDateChange() {
const m = moment(this.date);
this._bookingService.setDate(m, this.view);
}
【问题讨论】: