【发布时间】:2020-10-19 14:37:56
【问题描述】:
我有一个 Input 属性作为 setter:
@Input() set moduleData(value: any) {
this._moduleData = value;
this.destroy$.next();
this.destroy$.complete();
this.startAttempt();
}
startAttempt() {
if (!this.isExamStarted()) {
console.log("exam is not started");
interval(1000).pipe(takeUntil(this.destroy$)).subscribe((res) => {
if (
this.canStartAssessment(this.moduleData.module_progress.start_time)
) {
console.log("exam can be started now");
this.getTimeRemainingInExam();
} else {
this.getTimer(
this.moduleData.module_progress.start_time,
false
);
}
});
} else {
this.getTimeRemainingInExam();
}
}
ngOnDestroy(): void {
console.log("componenet destroyef");
this.destroy$.next();
this.destroy$.complete();
}
通过使用 takeUntil 运算符,我试图停止计时器。我可以看到即使在组件被销毁后计时器仍然运行。此外,当输入属性发生变化时,我可以看到在 1 秒内它被调用了两次。例如,日志打印两次,与先前值的输入一样多。再次开始区间前输入属性发生变化时如何清除所有区间?
【问题讨论】:
-
您的
interval的takeUntil(destroy$)永远不会完成。destory$在间隔开始之前已经完成。一旦流完成或出错,它就完成并且永远不会再次发出另一个值。对已完成的主题调用.next()无效。