首页 > 解决方案 > 一个组件上的运行按钮并在另一个组件上显示性能

问题描述

我开发了一项服务来运行计时器,一切都按预期工作。

在创建它的组件上运行计时器时,还可以在另一个组件上查看它是否正常工作?

试过但没有用:(

@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> 

标签: angulartypescript

解决方案


您还需要将服务添加到 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>  -->

在此处输入图像描述


推荐阅读