简体   繁体   English

在 Angular/rxjs 中使用异步管道时如何传递参数?

[英]How to pass parameters while using the async pipe in Angular/rxjs?

I'm trying to use the declarative approach in Angular, unwrapping observables with the async pipe and using OnPush change detection.我正在尝试在 Angular 中使用声明性方法,使用async管道OnPush可观察对象并使用OnPush更改检测。

I have a second observable, which may or may not be invoked, and needs data from the first observable to complete.我有第二个 observable,它可能会或可能不会被调用,并且需要来自第一个 observable 的数据才能完成。

order.component.html订单.component.html

<div *ngIf="order$ | async as order">
    <h3> Order {{ order.id }} </h3>
    ....
     
    <app-returns *ngIf="order.status === 'Returned'"
        [rma]="rma$ | async" >
    </app-returns>

</div>

order.component.ts订单.component.ts

order$: Observable<Order> = this.route.paramMap.pipe(
   map((params: ParmaMap) => +params.get('id')),
   switchMap((id: number) => 
       this.orderSvc.get(id)
));

rma$: Observable<Rma> = this.order$.pipe(
    switchMap((order: Order) => 
        this.rmaSvc.get(order.rma.id)
));

This issue with this approach is that the Order service makes two calls to the API to complete this.这种方法的问题在于订单服务对 API 进行了两次调用以完成此操作。

When I have multiple observables needed in the template, I'll usually use a forkJoin or combineLatest to combine them.当模板中需要多个 observable 时,我通常会使用forkJoincombineLatest来组合它们。 But in this case I only want to call the rma service if necessary.但在这种情况下,我只想在必要时调用 rma 服务。

Other, more naive approaches (while illustrating the issue well) have hilarious outcomes.其他更幼稚的方法(同时很好地说明了问题)会产生有趣的结果。 Can you say 429?你能说429吗?

 <app-returns *ngIf="order.status === 'Returned'"
    [rma]="rma$(order.rma.id) | async" >
 </app-returns>

Typescript打字稿

rma$(id: number): Observable<Rma> {
    return this.rmaSvc.get(id);
}

How do I pass a parameter while using the async pipe?使用异步管道时如何传递参数?

you can change your order observable using shareReplay for caching to :您可以使用shareReplay将可观察的订单更改为缓存:

order$: Observable<Order> = this.route.paramMap.pipe(
   map((params: ParmaMap) => +params.get('id')),
   switchMap((id: number) => 
       this.orderSvc.get(id)
   ),
   shareReplay(1)
);

and then create然后创建

rma$: Observable<Rma> = order$.pipe(
  switchMap((order: Order) => 
    this.rmaSvc.get(order.rma.id)
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM