Angular 2 - Countdown timer

别来无恙 提交于 2020-01-09 18:22:32

问题


I am willing to do a countdown timer in Angular 2 that start from 60 (i.e 59, 58,57, etc...)

For that I have the following:

constructor(){
  Observable.timer(0,1000).subscribe(timer=>{
  this.counter = timer;
});
}

The above, ticks every second, which is fine; however, it goes in an ascending order to an unlimited number. I am not sure if there is a way to tweak it so I can have a countdown timer.


回答1:


There are many ways to achieve this, a basic example is to use the take operator

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

@Component({
   selector: 'my-app',
   template: `<h2>{{counter$ | async}}</h2>`
})
export class App {
   counter$: Observable<number>;
   count = 60;

   constructor() {
     this.counter$ = timer(0,1000).pipe(
       take(this.count),
       map(() => --this.count)
     );
   }
}

A better way is to create a counter directive!

import { Directive, Input, Output, EventEmitter, OnChanges, OnDestroy } from '@angular/core';

import { Subject, Observable, Subscription, timer } from 'rxjs';
import { switchMap, take, tap } from 'rxjs/operators';

@Directive({
  selector: '[counter]'
})
export class CounterDirective implements OnChanges, OnDestroy {

  private _counterSource$ = new Subject<any>();
  private _subscription = Subscription.EMPTY;

  @Input() counter: number;
  @Input() interval: number;
  @Output() value = new EventEmitter<number>();

  constructor() {

    this._subscription = this._counterSource$.pipe(
      switchMap(({ interval, count }) =>
        timer(0, interval).pipe(
          take(count),
          tap(() => this.value.emit(--count))
        )
      )
    ).subscribe();
  }

  ngOnChanges() {
    this._counterSource$.next({ count: this.counter, interval: this.interval });
  }

  ngOnDestroy() {
    this._subscription.unsubscribe();
  }

}

Usage:

<ng-container [counter]="60" [interval]="1000" (value)="count = $event">
  <span> {{ count }} </span>
</ng-container>

Here is a live stackblitz




回答2:


Import into Component:

import { Observable } from "rxjs/Observable";
import "rxjs/add/observable/timer";
import "rxjs/add/operator/finally";
import "rxjs/add/operator/takeUntil";
import "rxjs/add/operator/map";

Function CountDown:

countdown: number;
 startCountdownTimer() {
    const interval = 1000;
    const duration = 10 * 1000;
    const stream$ = Observable.timer(0, interval)
      .finally(() => console.log("All done!"))
      .takeUntil(Observable.timer(duration + interval))
      .map(value => duration - value * interval);
    stream$.subscribe(value => this.countdown = value);
  }

Html :

<div class="panel panel-default">
  <div class="panel-heading">
    <h2 class="panel-title">Countdown timer</h2>
  </div>
  <div class="panel-body">
    <div>
      <label>value: </label> {{countdown}}
    </div>
    <div>
      <button (click)="startCountdownTimer()" class="btn btn-success">Start</button>
    </div>
  </div>
</div>


来源:https://stackoverflow.com/questions/44489580/angular-2-countdown-timer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!