angular - 进入页面时按钮自动启动
问题描述
我有两个组件(应用程序和导航栏)。当我单击表格行时,计时器启动。我想在所有其他组件中显示此计时器,因此我在服务中创建了一个返回 User 值的函数,因此可以在所有组件中显示计时器。
我的问题是当我启动页面时,导航栏按钮开始自动计数,我不知道为什么。此按钮应仅在单击应用程序组件时才起作用/显示结果。
有谁知道为什么会这样?
我的代码链接
应用服务
this.currentUserId = new BehaviorSubject<string>(undefined);
setUserId(id: string): void {
this.currentUserId.next(id);
}
应用组件
startTimer(data) {
this.currentusertime = data.key.ID;
this.taskService.iduser = data.key.ID;
this.taskService.startTimer(data.key.ID);
}
pauseTimer(data) {
this.taskService.iduser = data.key.ID;
this.taskService.pauseTimer(data.key.ID);
}
rowClicked(event: any): void {
this.taskService.setUserId(event.data.ID);
}
导航栏组件
constructor(public taskService: TaskService) {
this.taskService.currentUserId.subscribe(x => {
this.userId = x;
this.startTimer();
});
}
正如您在图像中看到的,导航栏上的按钮已经处于活动状态,但不知道为什么。只有在应用组件表上单击某些内容时才应启用它:(
解决方案
发生这种情况是因为您使用的是BehaviourSubject
. 它使用起始值或当前值(如果已更改)调用所有订阅。在您的情况下,您this.taskService.currentUserId.subscribe(x => {
将undefined
在页面加载时被调用。一个简单的解决方法是过滤掉undefined
值。
您实际上可以通过打印出taskService.timerForUsers
数组来测试该行为。这表明undefined
实际上创建了一个密钥:{ "undefined": { "currentState": "start", "currentTime": 75, "initialTime": 20, "startTime": "1578143992066", "interval": 134 } }
constructor(public taskService: TaskService) {
this.taskService.currentUserId.pipe(
filter(x => !!x) // subscribe will not trigger when x is falsy
).subscribe(x => {
this.userId = x;
this.startTimer();
});
}
在这里工作Stackblitz。
推荐阅读
- javascript - Ajax 多重上传
- r - 如何调用创建的变量,在 R 循环中向 i 添加后缀
- vb.net - 如何在开始 3 位置代码中动态使用插入索引位置而不是多个 if 语句
- python - 删除熊猫框架中的列
- service-worker - 用户退出后可以向用户发送推送通知吗?
- typescript - 包含另一个数组的 Array 的 TypesScript 通用语法
- c++11 - Codeforces 中的“诊断检测到问题 [cpp.g++17-drmemory]: ~~Dr.M~~ Dr. Memory 版本 1.11.0”错误是什么?
- javascript - 如何将Object的值映射到整个数组中其对应键的出现次数作为数组?
- javascript - JSX:按字母顺序对对象进行排序
- java - 为什么我在构造函数上收到 Selenium init 错误?