angular - 如何在 Angular 7 中停止间隔?
问题描述
我有一个连续发出值的函数。
我想要的是??
如果满足 Math.sign 条件,我会将用户重定向到另一个屏幕并显示一条 toast 消息。
但是现在,吐司消息是连续显示的,因为间隔是连续的。
我试过什么?
this.subscription.unsubscribe()
内部if(Math.sign)
条件,但它没有工作。
关于如何在以下代码中停止间隔的任何建议?
startTimer(validUntil: string) {
this.counter$ = interval(1000).pipe(
map((x) => {
this.diff = Math.floor((new Date(validUntil).getTime() - new Date().getTime()) / 1000);
if (Math.sign(this.diff) == -1) {
//Tried this.subscription.unsubscribe() here
// Redirects me to another component
this.goBack(true);
}
return x;
}));
this.subscription = this.counter$
.subscribe((x) => {
this.message$ = this.dhms(this.diff);
});
}
goBack(requestExpired: boolean) {
if (requestExpired == true) {
this.messageDialogService.presentToast('Expired')
}
this.router.navigate(['mypage']);
}
解决方案
恕我直言,takeWhile
内部条件是最明显的方法。
例如:
startTimer(validUntil) {
this.counter$ = interval(1000).pipe(
// turn value emissions into diffs
map(() => Math.floor((new Date(validUntil).getTime() - new Date().getTime()) / 1000)),
// this is needed to terminate when condition is met
takeWhile(diff => Math.sign(diff) !== -1),
// when terminated on conditions -- navigate back
finalize(()=>{
this.goBack(true);
})
// just in case if user navigates out before condition is met
takeUntil(this.destroy$)
)
.subscribe(diff => {
this.message$ = this.dhms(diff);
});
}
注意:然而,我怀疑你counter$
根本不需要。您只能使用message$
带有异步管道的流,例如
控制器
startTimer(validUntil) {
this.messages$ = interval(1000).pipe(
// ...
)
}
模板
<div>{ messages$ | async }</div>
希望这可以帮助
推荐阅读
- machine-learning - lightgbm python数据集参考参数是什么意思?
- elasticsearch - 过滤在弹性搜索中作为对象列表出现的值
- java - 如何阻止提供者使用阻塞队列变空?
- types - 将类型转换为字符串
- c++ - 为什么 EdsDownloadEvfImage() 总是返回 EDS_ERR_OBJECT_NOTREADY
- kubernetes - Redis 似乎在启动时删除了 dump.rdb。使用 Kubernetes PVC 和 KubeDB。为什么会这样?
- reactjs - 我正在尝试将 Firebase 电子邮件验证链接验证添加到我的应用程序,但出现错误“无法读取 null 的电子邮件属性”
- android - for循环中的变量是不可识别的,而不是在循环中声明和初始化的
- mysql - 如何在不破坏mysql中表排列的情况下选择表中特定的eid
- android - 在Android webview上限制html输入类型时间的宽度