在管道中寻找类似于rEl.js的OrElse之类的查找功能

我有以下代码。我要实现的目标是重定向到“查找”功能在可观察的已加载订单中找不到任何订单对象时找不到的页面。

private order: Observable<OrderModel>;

ngOnInit() {
    this.route.params.subscribe(params => {
    this.name = params.id;
    this.order = this.orderService.ordersLoaded.pipe(map((orders: OrderModel[]) => orders
          .find((order: OrderModel) => order.orderName === this.name.toUpperCase())));
 });

我尝试过类似的事情:

ngOnInit() {
    this.route.params.subscribe(params => {
    this.name = params.id;
    this.order = this.orderService.ordersLoaded.pipe(map((orders: OrderModel[]) => orders
        .find((order: OrderModel) => order.orderName === this.name.toUpperCase()),defaultIfEmpty(this.router.navigate(['/notFound']))
      ));
 });

但是它总是将我重定向到页面找不到组件。

shantianfang 回答:在管道中寻找类似于rEl.js的OrElse之类的查找功能

您可以点击运算符以存档所需的内容:

this.order = this.orderService.ordersLoaded.pipe(
      map((orders: OrderModel[]) => orders.find(order => order.orderName === this.name.toUpperCase()),tap(order => {
        if (!order) {
          this.router.navigate(['/notFound']);
        }
      })
    ));

您可以创建一些自定义rxjs运算符来摆脱if

export function tapIf<T>(
  predicate: (value: T) => boolean,fn: (x: T) => void
): MonoTypeOperatorFunction<T> {
  return input$ =>
    input$.pipe(
      tap(x => {
        if (predicate(x)) {
          fn(x);
        }
      })
    );
}

export function tapIfFalsy<T>(fn: (x: T) => void): MonoTypeOperatorFunction<T> {
  return tapIf<T>(x => !x,x => fn(x));
}

然后您的代码可以变得更加简单:

this.order = this.orderService.ordersLoaded.pipe(
      map((orders: OrderModel[]) => orders.find(order => order.orderName === this.name.toUpperCase()),tapIfFalsy(() => this.router.navigate(['/notFound']))
    ));
,

defaultIfEmpty()实际上仅在可观察到的完成但没有返回任何内容时触发, https://www.learnrxjs.io/operators/conditional/defaultifempty.html 与返回的值无关

您可以尝试下面的代码

zip(this.orderService.ordersLoaded,this.route.params).pipe(tap([orders,params])=>{
  this.name = params.id;
  if(!orders.find(order=>order.orderName === this.name.toUpperCase())
        this.router.navigate(['/notFound'])
}).subscribe()
本文链接:https://www.f2er.com/3166833.html

大家都在问