chirag
chirag

Reputation: 1779

How to do some action after retrieving data using async pipe in angular 10

I am using async pipe to bind data as below: (Angular 10)

app.component.html:

<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody *ngFor="let customer of customers | async">
        <tr>
            <td>{{customer.id}}</td>
            <td>{{customer.name}}</td>
        </tr>
    </tbody>
</table>

app.component.ts:

constructor(private customersService: CustomersService) { }
    customers:Observable<any>;
    ngOnInit() {
        this.customers = this.customersService.getCustomers();
      }

Here I am calling getCustomers() method, which fetch data from api via http GET method and assigning to customers observable.

It works correctly. I want to do some action after retrieving data from api.

So how to achieve this using async pipe ?

Upvotes: 2

Views: 2096

Answers (2)

Barremian
Barremian

Reputation: 31105

You could pipe in a tap operator to the source to perform some side-effects.

ngOnInit() {
  this.customers = this.customersService.getCustomers().pipe(
    tap(res => {
      // do something with `res`
    })
  );
}

The actions inside the tap will be performed for each notification from the observable and does not affect the source notification.

Working example: Stackblitz

Upvotes: 5

Ganesh
Ganesh

Reputation: 6016

Async acts like subscription and prevents the memory leaks. To perform any action we can use map or filter to manipulate the data.

You can do something like below,

 ngOnInit() {
     this.customers = this.customersService.getCustomers().map(resp => {
          // do the actions you want
     });
 }

Happy Coding.. :)

Upvotes: 0

Related Questions