首页 > 解决方案 > 从开始秒数开始的计时器角度计数

问题描述

如何从某个开始的秒数开始在 Angular 中进行倒计时?另外,如果可能的话,我需要格式为 hh:mm:ss。

我试图做这样的事情,从模板调用 getAlarmDuration ,持续时间以秒为单位。

getAlarmDuration(duration: number): any {
    this.countStart = duration;
    setInterval(this.setTime, 1000);
  }

  setTime(): void {
    ++this.countStart;
    console.log(this.pad(parseInt((this.countStart / 60).toString(), 10)) + ':' + this.pad(this.countStart % 60))
  }

  pad(val: any): string {
    var valString = val + "";
    if (valString.length < 2) {
      return "0" + valString;
    }
    else {
      return valString;
    }
  }

提前致谢。

标签: javascriptangulartypescripttimercounter

解决方案


您可以使用“rxjs”中的间隔并将计数器映射到所需的结果。

import { Component } from '@angular/core';
import { interval } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Count';
  currentSeconds = 60;

  // interval will emit every 1000ms
  count$ = interval(1000).pipe(
    // transform the stream to the result you want -- hh:mm:ss 
    map(count => this.format(count + this.currentSeconds * 1000))
  );

  format(seconds: number): string {
    return new Date(seconds + +new Date()).toLocaleString('en-EN', {
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  }
}

这是一个指向 stackblitz示例工作示例的链接


推荐阅读