admin管理员组文章数量:1400007
I try to implement a countdown timer in angular 6 using rxjs 6. I also need to be able to subscribe to results and to reset the timer:
What I tried:
var timer = interval(1000).pipe(
take(4)
);
timer.subscribe(x => console.log(x));
Result:
0
1
2
3
What I need is to reverse the timer to count from 3 to 1
I found this coundown function to implement reverse count, but I cannot subscribe to it, like in first example
interval(1000).pipe(
map((x) => { console.log( x) })
);
Result:
empty
I try to implement a countdown timer in angular 6 using rxjs 6. I also need to be able to subscribe to results and to reset the timer:
What I tried:
var timer = interval(1000).pipe(
take(4)
);
timer.subscribe(x => console.log(x));
Result:
0
1
2
3
What I need is to reverse the timer to count from 3 to 1
I found this coundown function to implement reverse count, but I cannot subscribe to it, like in first example
interval(1000).pipe(
map((x) => { console.log( x) })
);
Result:
empty
Share Improve this question asked Apr 9, 2019 at 9:24 AlexFF1AlexFF1 1,2934 gold badges25 silver badges47 bronze badges3 Answers
Reset to default 4You can use timer instead of interval, to actually implement the countdown you should map the timer result like this: map(i => countdownStart - i)
const countdownStart = 3;
Rx.Observable
.timer(1000, 1000)
.map(i => countdownStart - i)
.take(countdownStart + 1)
.subscribe(i => console.log(i));
Logs: 3 2 1 0
Another possible solution is to use the range operator.
Rx.Observable
.range(0, countdownStart + 1)
.map(i => countdownStart - i)
.subscribe(i => console.log(i));
Logs: 3 2 1 0
Here is how I do it with TimerObservable
. Remember to unsubscribe on destroy.
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();
}
}
How about?
var timer = interval(1000).pipe(
take(4),
map(x => 3 - x)
);
timer.subscribe(console.log);
本文标签: javascriptrxjs 6 countdown timer subscribe angular 6Stack Overflow
版权声明:本文标题:javascript - rxjs 6 countdown timer subscribe angular 6 - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744643865a2617280.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论