我愿意在Angular 2中做一个从60开始的倒计时器(即59,58,57等......)
为此,我有以下内容:
constructor(){
Observable.timer(0,1000).subscribe(timer=>{
this.counter = timer;
});
}
以上,每秒滴答,这很好;但是,它按升序排列为无限数量。 我不确定是否有办法调整它,所以我可以有一个倒数计时器。
答案 0 :(得分:26)
有很多方法可以实现这一点,一个基本的例子是使用take
运算符
import { Observable, timer } from 'rxjs';
import { take, map } from 'rxjs/operators';
@Component({
selector: 'my-app',
template: `<h2>{{countDown | 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, SubscriptionLike, timer } from 'rxjs';
import { switchMap, take, tap } from 'rxjs/operators';
@Directive({
selector: '[counter]'
})
export class CounterDirective implements OnChanges, OnDestroy {
private counter$ = new Subject<any>();
private countSub$: SubscriptionLike;
@Input() counter: number;
@Input() interval: number;
@Output() value = new EventEmitter<number>();
constructor() {
this.countSub$ = this.counter$.pipe(
switchMap((options: any) =>
timer(0, options.interval).pipe(
take(options.count),
tap(() => this.value.emit(--options.count))
)
)
).subscribe();
}
ngOnChanges() {
this.counter$.next({ count: this.counter, interval: this.interval });
}
ngOnDestroy() {
this.countSub$.unsubscribe();
}
}
<强>用法:强>
<ng-container [counter]="60" [interval]="1000" (value)="count = $event">
<span> {{ count }} </span>
</ng-container>
这是一个实时stackblitz
答案 1 :(得分:2)
导入组件:
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>