Search code examples
angularrxjsrxjs6

How to create some timers and show result from them?


I have create timer using RXJS:

let timer1value = null;
let timeFinish =  30;
let finishDate = new Date();

return timer(1000)
      .pipe(
        takeWhile(() => new Date() < finishDate),
        finalize(() => {
          timeFinish = finishDate;
        })
      )
      .subscribe((t) => {
      timer1value = t;
});

I need to create some timers and show result on the page:

{{timer1value}}

So, I have added observer to array this.timers:

this.timers.push(timer(1000)
      .pipe(
        takeWhile(() => new Date() < finishDate),
        finalize(() => {
          timeFinish = finishDate;
        })
      ));

Then how to get in template actual value of each timers in subscription?


{{timer2value}}

{{timerNvalue}}```

Solution

  • In Angular you can use the AsyncPipe to show the latest value emitted by Observables.

    To show the latest value of the first timer in the array you can write:

    {{timers[0] | async}}