Angular 2 - 倒数计时器 [英] Angular 2 - Countdown timer
本文介绍了Angular 2 - 倒数计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我愿意在 Angular 2 中做一个从 60 开始的倒数计时器(即 59、58,57 等...)
I am willing to do a countdown timer in Angular 2 that start from 60 (i.e 59, 58,57, etc...)
为此,我有以下几点:
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.
推荐答案
有很多方法可以实现,一个基本的例子就是使用take
操作符
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)
);
}
}
更好的方法是创建一个反指令!
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();
}
}
用法:
<ng-container [counter]="60" [interval]="1000" (value)="count = $event">
<span> {{ count }} </span>
</ng-container>
这是一个实时stackblitz
这篇关于Angular 2 - 倒数计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文