[英]rxjs 6 countdown timer subscribe angular 6
我嘗試使用rxjs 6在angular 6中實現倒數計時器。我還需要能夠訂閱結果並重置計時器:
我試過的
var timer = interval(1000).pipe(
take(4)
);
timer.subscribe(x => console.log(x));
結果:
0
1
2
3
我需要將計時器從3改為1
我發現此coundown函數可實現反向計數,但我無法訂閱它,如第一個示例
interval(1000).pipe(
map((x) => { console.log( x) })
);
結果:
空
您可以使用計時器而不是間隔來實際實施倒計時,您應該像這樣map(i => countdownStart - i)
計時器結果: map(i => countdownStart - i)
const countdownStart = 3;
Rx.Observable
.timer(1000, 1000)
.map(i => countdownStart - i)
.take(countdownStart + 1)
.subscribe(i => console.log(i));
日志:3 2 1 0
另一種可能的解決方案是使用范圍運算符。
Rx.Observable
.range(0, countdownStart + 1)
.map(i => countdownStart - i)
.subscribe(i => console.log(i));
日志:3 2 1 0
怎么樣?
var timer = interval(1000).pipe(
take(4),
map(x => 3 - x)
);
timer.subscribe(console.log);
這是我使用TimerObservable
。 記得退訂銷毀書。
import {TimerObservable} from "rxjs/observable/TimerObservable";
import { Subscription } from 'rxjs';
export class MyComponent implements OnInit, OnDestroy {
private sub: Subscription;
ngOnInit() {
// Delay 0 seconds, run every second
let timer = TimerObservable.create(0, 1000);
let number = 3;
this.sub = timer.subscribe(t => {
if(number !== 0) {
console.log(number);
number--;
}
});
}
ngOnDestroy(): void {
this.sub.unsubscribe();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.