Angular Rxjs观察者过滤器不工作,出现错误

Angular Rxjs观察者过滤器不工作,出现错误,angular,rxjs,behaviorsubject,rxjs-observables,rxjs-pipeable-operators,Angular,Rxjs,Behaviorsubject,Rxjs Observables,Rxjs Pipeable Operators,我的服务中有以下代码 let b = new BehaviorSubject({ a: undefined }) let o = b.asObservable(); o.pipe(filter(_ => _.a === 5)).subscribe(() => { debugger; }, error => { debugger }) b

我的服务中有以下代码

        let b = new BehaviorSubject({ a: undefined })
        let o = b.asObservable();
        o.pipe(filter(_ => _.a === 5)).subscribe(() => {
            debugger;
        }, error => {
            debugger
        })
        b.next({ a: 10 })
        b.next({ a: 5 })
        b.error({ a: 10 })
当我调用b.next({a:10})时,它不会命中onNext回调中的调试器;当我调用b.next({a:5})时,它会命中onNext回调中的调试器。 当我调用b.error({a:10})时,它会在onError回调中命中调试器

我的期望是,由于不满足筛选条件,因此不应调用onError回调。但是,很明显我这里出了点问题

我如何过滤错误呢


提前谢谢。

您无法筛选
错误
s,原因与您无法筛选
完成
s相同。这没有道理。他们发出了溪流结束的信号。你不能过滤结尾

当然,您可以捕获一个错误,然后什么也不做——这感觉有点像过滤错误

o.pipe(
  catchError(err => 
    err?.a === 5 ?
    return of(err) :
    EMPTY
  ),
  filter(val => val.a === 5)
).subscribe({
  next: val => debugger,
  error: err => debugger,
  complete: () => debugger
});
当然,在你出错或完成后发送给主题的任何东西都不会起任何作用

    b.next({ a: 10 }); // Filtered, not emitted
    b.next({ a: 5 }); // value emitted
    b.error({ a: 5 }); // caught and new non-error { a: 5 } emitted as value. subject 'b' is done
    b.next({ a: 5 }); // Does nothing
由于受试者出错/完成,最后一次呼叫将无效

同样地:

    b.next({ a: 10 }); // Filtered, not emitted
    b.next({ a: 5 }); // value emitted
    b.complete(); // subject 'b' is done
    b.next({ a: 5 }); // Does nothing
最后:

    b.next({ a: 10 }); // Filtered, not emitted
    b.next({ a: 5 }); // value emitted
    b.error({ a: 10 }); // caught and not emitted. subject 'b' is done
    b.next({ a: 5 }); // Does nothing

您无法筛选
错误
s,原因与您无法筛选
完成
s相同。这没有道理。他们发出了溪流结束的信号。你不能过滤结尾

当然,您可以捕获一个错误,然后什么也不做——这感觉有点像过滤错误

o.pipe(
  catchError(err => 
    err?.a === 5 ?
    return of(err) :
    EMPTY
  ),
  filter(val => val.a === 5)
).subscribe({
  next: val => debugger,
  error: err => debugger,
  complete: () => debugger
});
当然,在你出错或完成后发送给主题的任何东西都不会起任何作用

    b.next({ a: 10 }); // Filtered, not emitted
    b.next({ a: 5 }); // value emitted
    b.error({ a: 5 }); // caught and new non-error { a: 5 } emitted as value. subject 'b' is done
    b.next({ a: 5 }); // Does nothing
由于受试者出错/完成,最后一次呼叫将无效

同样地:

    b.next({ a: 10 }); // Filtered, not emitted
    b.next({ a: 5 }); // value emitted
    b.complete(); // subject 'b' is done
    b.next({ a: 5 }); // Does nothing
最后:

    b.next({ a: 10 }); // Filtered, not emitted
    b.next({ a: 5 }); // value emitted
    b.error({ a: 10 }); // caught and not emitted. subject 'b' is done
    b.next({ a: 5 }); // Does nothing

一个可观察到的错误只能发生一次。您不能发送多个错误通知。您可以使用
catchError
捕捉错误,并返回要切换到的可观察对象。谢谢@fridoo的帮助。现在我明白了为什么它不能像我期望的那样工作了。一个可观察的物体只能出错一次。您不能发送多个错误通知。您可以使用
catchError
捕捉错误,并返回要切换到的可观察对象。谢谢@fridoo的帮助。现在我明白为什么它不能按我预期的方式工作了。谢谢。这很有道理,谢谢。这是有道理的。