我使用异步管道绑定数据,如下所示:(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();
}
这里我调用getCustomers((方法,该方法通过http GET方法并分配给可观察的客户。
它工作正常。我想在从api中检索数据后执行一些操作。
那么如何使用异步管道来实现这一点呢?
您可以通过管道将tap
运算符发送到源以执行一些副作用。
ngOnInit() {
this.customers = this.customersService.getCustomers().pipe(
tap(res => {
// do something with `res`
})
);
}
tap
内部的操作将针对可观察到的每个通知执行,并且不会影响源通知。
工作示例:Stacklitz
Async
的作用类似于订阅,可以防止内存泄漏。要执行任何操作,我们可以使用映射或过滤器来操作数据。
你可以做下面这样的事情,
ngOnInit() {
this.customers = this.customersService.getCustomers().map(resp => {
// do the actions you want
});
}
快乐编码..:(