angular - 激活组件上的按钮并继续计数直到停止
问题描述
我正在尝试实现一个计时器。
我的问题是:我启动了计时器,但是每当我更改页面时,计时器都会重置/我必须再次启动它:(
目标是启动计时器时,它仅在单击暂停时停止,如果我单击开始并且可以更改计时器始终处于活动状态的页面。
谁能帮我?
我离开下面,我的示例的链接,计时器在服务选项卡中......当我切换到家并返回服务以查看时间......它被禁用,我打算让它始终保持活动状态
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);
}
解决方案
通过使用服务,您可以保留数据,直到您刷新浏览器。我浏览了您的代码并在服务文件夹中添加了一项帮助服务。不要混淆服务(意味着角度服务)和服务(您的组件服务)。就在您离开服务组件之前,您需要更新角度服务中的两个变量。一个是计时器是否暂停,另一个是当时的计时器计数。我们*可以在服务组件的 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;
}
}
推荐阅读
- amazon-web-services - EC2 实例配置文件策略创建
- amazon-web-services - AWS CodePipeline ApplicationStop 生命周期事件失败
- python - 使用 pip 安装特定版本的 vtk
- reactjs - 带有 React Hooks 的受控/非受控输入字段
- php - 带有自定义模块的 Drupal 8/9 覆盖树枝
- ios - 无法从其模块界面构建模块“Razorpay”
- python - 有没有办法舍入非常大的分数,如 3.7625745528893614e-83?
- vb.net - 如何在 VB.NET 中实现 lambda 表达式(错误:表达式不是方法)
- html - 我如何更改圆圈内的徽标大小
- python - 在 Python 函数中使用 **kwargs