首页 > 解决方案 > 进入页面时按钮自动启动

问题描述

我有两个组件(应用程序和导航栏)。当我单击表格行时,计时器启动。我想在所有其他组件中显示此计时器,因此我在服务中创建了一个返回 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();
    });
  }

正如您在图像中看到的,导航栏上的按钮已经处于活动状态,但不知道为什么。只有在应用组件表上单击某些内容时才应启用它:(

图片

标签: angulartypescript

解决方案


发生这种情况是因为您使用的是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


推荐阅读