angular - 一个组件上的运行按钮并在另一个组件上显示性能
问题描述
我开发了一项服务来运行计时器,一切都按预期工作。
在创建它的组件上运行计时器时,还可以在另一个组件上查看它是否正常工作?
试过但没有用:(
@Input() button: boolean = false;
<p *ngIf="button">{{servicesService.fetchDisplay()}}</p>
<app-services [button]="true"></app-services>
这样,所有服务组件都出现在另一个组件中,但计时器不起作用。
服务
startTimer() {
this.interval = setInterval(() => {
if (this.time === 0) {
this.time++;
} else {
this.time++;
}
this.display = this.transform(this.time);
return this.display;
}, 1000);
}
HTML
<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>
<p >{{servicesService.fetchDisplay()}}</p>
解决方案
您还需要将服务添加到 About 组件中[将其保存在另一个组件中以从两个地方控制计时器],如下所示:
import { Component, OnInit } from '@angular/core';
import { ServicesService } from '../services/services.service';
@Component({
selector: 'app-about',
templateUrl: './about.component.html',
styleUrls: ['./about.component.css']
})
export class AboutComponent implements OnInit {
constructor(private servicesService: ServicesService) { }
ngOnInit() {
}
startTimer() {
this.servicesService.startTimer();
}
pauseTimer() {
this.servicesService.pauseTimer();
}
}
.container {
width: 100%;
height: 400px;
border: solid blue 2px;
border-radius: 5px;
}
<div class="container" >
<h1> This is the about component </h1>
<h3> Click on Home for instructions </h3>
<p >{{servicesService.fetchDisplay()}}</p>
<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>
</div>
<!-- <app-services [button]="true"></app-services> -->
推荐阅读
- python - PyQT5:在 qsql 中不维护 SpinBox 值
- wordpress - 使用 Timber 获取 ACF OEmbed URL 而不返回 iFrame
- python - 无法编码或解码以在我的字符串上看到“ç”
- javascript - 如何在反应中停止递归 setTimeout 函数(clearTimeout 不起作用)?
- python-3.x - 使用 Boto3 删除 SQS 消息时如何防止连接超时
- scala - 使用 akka-http 模板的新 sbt 应用程序,如何确定解析器并添加 maven Central?
- microsoft-graph-api - 通过 Graph API 创建 OneNote 页面时设置页面顺序
- php - 避免使用 foreach 重复 3 次相同的功能
- rust - 将两个对象传递给线程
- python - 如何在尝试使用 pip 安装某些依赖项时修复错误