首页 > 解决方案 > Angular - RxJS - 如何对链中的过滤项目执行操作?

问题描述

我有这样的管道:

this.parentFormControl.valueChanges
  .pipe(
    debounceTime(500),
    distinctUntilChanged(),
    tap(() => {
      this.focusIndex = -1;
    }),
    filter(() => this.myCondition()),
    switchMap((value: string) => {
      return this.http.get(value).pipe(catchError(err => {
        this.myErrorFunction(err);
        return EMPTY;
      }));
    })
  )

而且我想执行一些其他的“侧面”操作,例如在点击操作符中,对于过滤的项目 - 删除 - (可以说从“myCondition()”返回“false”)我该怎么做?

标签: angularrxjsangular6rxjs6

解决方案


您可以使用拆分链multicast,然后添加tap两个条件,然后简单地忽略您不想要的结果:

range(1, 10)
  .pipe(
    multicast(() => new Subject(),
      o => merge(
        o.pipe(
          filter(v => v % 2 === 0),
          tap(v => console.log('true', v)),
        ),
        o.pipe(
          filter(v => v % 2 !== 0),
          tap(v => console.log('false', v)),
          ignoreElements(),
        ),
      )
    ),
  )
  .subscribe(v => console.log('result', v));

它有点长,但它正确地将源分成两个链。

现场演示:https ://stackblitz.com/edit/rxjs6-demo-yarhux?file=index.ts


推荐阅读