Angular 按钮在进入页面时自动启动

Angular 按钮在进入页面时自动启动,angular,typescript,Angular,Typescript,我有两个组件(应用程序和导航栏)。 当我单击表格行时,计时器启动。我希望在所有其他组件中显示该计时器,因此我在服务中创建了一个函数,该函数返回User的值,因此可以在所有组件中显示计时器 我的问题是,当我启动页面时,导航栏按钮开始自动计数,我不知道为什么。此按钮应仅在单击应用程序组件时工作/显示结果 有人知道为什么会这样吗 我的代码 应用程序服务 this.currentUserId = new BehaviorSubject<string>(undefined); setUs

我有两个组件(应用程序和导航栏)。 当我单击表格行时,计时器启动。我希望在所有其他组件中显示该计时器,因此我在服务中创建了一个函数,该函数返回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();
    });
  }
如图所示,导航栏上的按钮已处于活动状态,不知道原因。仅当在应用程序组件表上单击某些内容时,才应启用该功能:(


发生这种情况是因为您使用的是
行为主题。它使用起始值或当前值调用所有订阅(如果已更改)。在您的情况下,您的
this.taskService.currentUserId.subscribe(x=>{
将在页面加载时使用
未定义的
调用。一个简单的解决方法是过滤掉
未定义的

实际上,您可以通过打印用户的
taskService.timer
数组来测试该行为。这表明实际创建了一个
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();
    });
  }

工作。

问题在于,在
TaskService
中,一旦打开
NavBar
组件,
startTimer()
就会触发。因此,通过这种方式,
*ngIf
不会传递以下内容:

*ngIf="taskService.getCurrentState() === 'pause' || taskService.getCurrentState() === undefined"
startTimer(userId:string) {   
    // ... rest
    currentUserTimer.currentState = 'start';
    this.state = currentUserTimer.currentState;
    // ... rest
}
对于所提到的
*ngIf
如果
getCurrentState()
返回
pause
undefined
,则它应该表示
play
按钮。但是您有一个不同的值
start

TaskService
中,您有以下内容:

*ngIf="taskService.getCurrentState() === 'pause' || taskService.getCurrentState() === undefined"
startTimer(userId:string) {   
    // ... rest
    currentUserTimer.currentState = 'start';
    this.state = currentUserTimer.currentState;
    // ... rest
}
这就是为什么
getCurrentState()
start
值的原因


我希望这会有帮助!

只有一个问题,当我启动计数器然后刷新页面时,它没有得到与应用程序组件中运行的组件相同的值。你知道为什么吗?感谢你的大力帮助!你没有在保存用户时保存用户ID。当页面重新加载时,行为主题中的值现在回到未定义的
。你也必须保存值。这里是另一个Stackblitz,一旦你掌握了窍门,它实际上就是。只是学习曲线有点陡峭。不客气!:)好事情是,有人仍然喜欢帮助别人!