首页 > 解决方案 > 激活组件上的按钮并继续计数直到停止

问题描述

我正在尝试实现一个计时器。

我的问题是:我启动了计时器,但是每当我更改页面时,计时器都会重置/我必须再次启动它:(

目标是启动计时器时,它仅在单击暂停时停止,如果我单击开始并且可以更改计时器始终处于活动状态的页面。

谁能帮我?

我离开下面,我的示例的链接,计时器在服务选项卡中......当我切换到家并返回服务以查看时间......它被禁用,我打算让它始终保持活动状态

堆栈闪电战

html

<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>

<p>{{display}}</p> 

组件.ts

startTimer() {
    this.interval = setInterval(() => {
        if (this.time === 0) {
            this.time++;
        } else {
            this.time++;
        }
        this.display = this.transform(this.time)
    }, 1000);
}

transform(value: number): string {
    var sec_num = value;
    var hours = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
    var seconds = sec_num - (hours * 3600) - (minutes * 60);

    return hours + ':' + minutes + ':' + seconds;
}

pauseTimer() {
    clearInterval(this.interval);
}    

标签: angulartypescript

解决方案


通过使用服务,您可以保留数据,直到您刷新浏览器。我浏览了您的代码并在服务文件夹中添加了一项帮助服务。不要混淆服务(意味着角度服务)和服务(您的组件服务)。就在您离开服务组件之前,您需要更新角度服务中的两个变量。一个是计时器是否暂停,另一个是当时的计时器计数。我们*可以在服务组件的 ngOnDestroy() 生命周期钩子中做到这一点。当我们回到服务组件时,我们将从角度服务中获取过去的信息,并相应地显示计时器。

下面是一段代码。在服务文件夹中添加 timer.service.ts 文件并编写以下代码。

import { Injectable, Inject } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class TimerService {
  time:number = 0;
  timerState:any;
}

将您的服务组件修改为以下。

import { Component, OnInit, OnDestroy } from '@angular/core';
import {TimerService} from './timer.service';

@Component({
  selector: 'app-services',
  templateUrl: './services.component.html',
  styleUrls: ['./services.component.css']
})
export class ServicesComponent implements OnInit, OnDestroy {

  constructor(private timerService: TimerService) { }

  ngOnInit() {
    this.time = this.timerService.time;
    if(this.timerService.timerState === 'visible_on') {
      this.startTimer();
    } else if(this.timerService.timerState === 'visible_off'){
      this.display = this.transform(this.timerService.time);
    }
  }
interval;
  time = 0;
  display:any;

startTimer() {
    this.interval = setInterval(() => {
      if (this.time === 0) {
        this.time++;
      } else {
        this.time++;
      }
      this.display=this.transform( this.time);
      this.timerService.timerState = 'visible_on';
    }, 1000);
  }

      transform(value: number): string {
      var sec_num = value; 
    var hours   = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
    var seconds = sec_num - (hours * 3600) - (minutes * 60);

    return hours+':'+minutes+':'+seconds;
    }

  pauseTimer(data,row) {
    this.timerService.timerState = 'visible_off';
    clearInterval(this.interval);

  }
  ngOnDestroy() {
    this.timerService.time = this.time;
  }
}

推荐阅读