blackHawk blackHawk - 13 days ago 8
Javascript Question

How to get number of ticks from rxjs Observable

How to get how many times this observable ran

this.clock = Observable.interval(1000).map(function(value){
if(value == 0){
return value * 100 / 60;
}
return value * 100 / 60;
}).take(61);


I want to get that this Observable ran 1 or 2 or 3.. times and display each time with interpolation in template

if I'm doing this, it would return percentage variable to be NaN

this.clock.subscribe(function(x){
console.log(x);
console.log("percentage " + this.percentage);
this.percentage = this.percentage + 1;
})

Answer

Then you can create a variable which will responsible for storing count of how many time observable ran. Then apply async over that value to display value returned by observable.

{{ clockCount | async }}

Code

clockCount: any;
count: number = 0;
ngOnInit(){
    this.clock = Observable.interval(1000).map((value) => {
       if(value == 0){
         return  value * 100 / 60;
       }
       return value * 100 / 60;
    }).take(61);
    this.clockCount = this.clock.do(() => this.count = ++this.count);
}