Home > other >  [Angular]: Tap on to an observable that has been used in template with async pipe
[Angular]: Tap on to an observable that has been used in template with async pipe

Time:08-27

I have an observable in an angular component that emits a value in 2 seconds interval. In the template I am printing that observable with async pipe and in the component class, I have piped a tap operator on to that observable to get updates.

Code: app.component.ts

import { Component, OnInit, VERSION } from '@angular/core';
import { Observable, share, shareReplay, tap } from 'rxjs';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  name = 'Angular '   VERSION.major;

  obs = new Observable((observer) => {
    let i = 0;
    setInterval(() => {
      observer.next(i  );
    }, 2000);
  })

  ngOnInit() {
    this.obs.pipe(share(),tap((data) => {
      console.log(data); //should print 1,2,3
    }));
  }

}

app.component.html

<hello name="{{ name }}"></hello>
<p>{{ obs | async }}</p>

But the tap operator is not executing here. As the async operator already subscribes to the observable, what is the way that I can tap on that observable and get updates?

stackblitz code example

CodePudding user response:

Use a pipe when creating the observable, and instead of setInterval there is an interval:

obs = interval(2000)
  .pipe(
    // map()
    share(),
    tap((data) => {
      console.log(data);
    }),
  );
  • Related