angular 10 中使用异步管道检索数据后如何执行某些操作

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

我正在使用异步管道绑定数据如下:(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.

它工作正常。我想在从 api.

检索数据后执行一些操作

那么如何使用异步管道实现这一点?

Async 就像订阅一样,防止内存泄漏。要执行任何操作,我们可以使用 map 或 filter 来操作数据。

您可以执行如下操作,

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

快乐编码..:)

您可以将 tap 运算符通过管道传输到源以执行某些 side-effects.

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

tap 中的操作将针对来自 observable 的每个通知执行,并且不会影响源通知。

工作示例:Stackblitz