Angular 2 - 倒数计时器从几分钟切换到几秒钟?

时间:2018-05-16 19:17:10

标签: angular rxjs countdowntimer

我有一个从5分钟开始的计时器(不显示秒数)。当它达到1分钟时,我如何切换它几秒钟?

示例:5分钟,4分钟,3分钟,......,1分钟,60秒,59,58,......,0。

import { timer } from 'rxjs/observable/timer';
import { take, map } from 'rxjs/operators';

@Component({
   selector: 'my-app',
   template: `<h2>{{countDown | async}} minute</h2>`
})
export class App {
   countDown;
   countInMinutes = 5;
   countInSeconds = 60;

   constructor() {

       this.countDown = timer(0,60000).pipe(
          take(this.countInMinute),
          map(()=> --this.countInMinute)
       );

       this.countDown = timer(0,1000).pipe(
          take(this.countInSec),
          map(()=> --this.countInSec)
       );
   }
}

1 个答案:

答案 0 :(得分:1)

首先,让我们只使用一个具有第二精度的计时器。要显示此值,有许多不同的方法。我们将选择为此创建自己的管道:

@Pipe({
  name: "timeRemaining",
})
export class TimeRemainingPipe implements PipeTransform {
  transform(value: number) {
    if (value <= 60) {
      return `${value} seconds`;
    }

    const minutesRemaining = Math.ceil(value / 60);
    return `${minutesRemaining} minutes`;
  }
}

我们现在可以编写一个这样的简单组件(根据您的喜好进行修改,您的问题与显示有关):

@Component({
  selector: "app-countdown",
  template: `
    <div *ngIf="!!timerSub">{{ value | timeRemaining }}</div>
    <button (click)="startTimer()" [disabled]="!!timerSub">Start</button>
  `,
})
export class AppCountdownComponent implements OnDestroy {
  public timerSub: Subscription;
  public value: number;

  public startTimer() {
    // For demonstration purposes
    const startValue = 1 * 60 + 5;

    this.timerSub = timer(0, 1000).pipe(
      take(startValue + 1),
      map(value => startValue - value)
    ).subscribe(
      value => this.value = value, 
      null, 
      () => this.timerSub = null
    );
  }

  ngOnDestroy() {
    if (this.timerSub) {
      this.timerSub.unsubscribe();
    }
  }
}

Here's a Stackblitz您可以在其中看到它。