Can I catch certain errors before “subscribe()” in an RXJS observable in Angular2?

前端 未结 2 1364
感动是毒
感动是毒 2021-01-18 20:44

Is it possible for a base class to catch certain errors before allowing the subclass to subscribe to the observable in Angular2.

e.g.

相关标签:
2条回答
  • 2021-01-18 21:19

    .catch() is the right one.

    Observable is lazy, so there are no errors before you subscribe. Not sure if you mean this kind of "before" therefore I mention it just to be sure.

    0 讨论(0)
  • 2021-01-18 21:20

    Using catch alone does not help much since you have client code subscribed and you must return Observable from catch.

    I would implement it as follows:

    Rx.Observable.of(42)
    .do(v=>{throw new Error('test')})
    .catch(Rx.Observable.of(undefined))
    .filter(v=>{return v !== undefined})
    .subscribe(
    (e)=>{console.log('next', e)}, 
    (e)=>{console.log('error', e)}, 
    ()=>{console.log('complete')}
    );
    
    0 讨论(0)
提交回复
热议问题