【问题标题】:How to ignore an error after catching it and execute final result in rxjs forkJoin?如何在捕获错误后忽略错误并在 rxjs forkJoin 中执行最终结果?
【发布时间】:2018-04-03 17:28:19
【问题描述】:
   myfunc() { 
        const combined = forkJoin(

            this.service.fn1(parameter).pipe(
                catchError(err => {
                   throw (this.handleError(err));
                }),
            ),

            this.service2.fn2().pipe(
                catchError(err => 
                //i need to ignore this error and execute final result,
            ), 

            this.service3.fn3().pipe(
                catchError(err => // Need to ignore this error too and continue)
            ));

         const subscribe = combined.subscribe (
            ([fn1,fn2,fn3]) => {

               //execute this part even if fn2, fn3 call fails. How can i do ??     

          }    
     );
}

如何忽略在 service2.fn2() 和 service3.fn3() 中捕获的错误并执行最后一部分?

我是新手,如有任何帮助,我们将不胜感激。

我看到了这个链接,但我没有完全理解。如果有人能简单地说出来,那就太好了。

http://jsbin.com/babirakiyi/1/edit?js,console

【问题讨论】:

  • 只需在catchError 中返回empty(),例如:catchError(() => empty())
  • 不要在 catch 错误中抛出错误
  • @martin 如果我添加 empty(),它不会执行最终结果部分!
  • @Ricardo 我需要为函数 1 显示不同的输出,所以我在那里抛出并执行一些操作。有没有其他办法?

标签: angular error-handling rxjs fork-join


【解决方案1】:

订阅方法接受 3 个函数参数,正如您在他的实现中看到的那样

subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription;

使用第二个来处理你的错误

更新

你的函数看起来像

myfunc() { 
const combined = forkJoin(
    this.service.fn1(parameter),
    this.service2.fn2(),
    this.service3.fn3())   

  const subscribe = combined.subscribe (
        ([fn1,fn2,fn3]) => {
           //execute this part even if fn2, fn3 call fails. How can i do ??     
      }, (err)=>{
          // here you can manage the side effect action
      }    
 );
}

如果抛出错误,将执行第二个函数

UDPATED #2

如果您想独立处理错误,您可以捕获每个错误

       const combined = forkJoin(
        this.service.fn1(parameter).catch((err)=>{ 
        // do your side effect 
        return Observable.of(undefined) 
        }),
        this.service2.fn2().catch(/** same idea*/),
        this.service3.fn3().catch(/** same idea*/)) 

请注意,对于每个失败的 observable,您将在订阅数组上收到 undefined

【讨论】:

  • 感谢您的帮助。正如我所说,我是新手,您可以在我的示例中添加它并展示我如何实现它吗?
  • 非常感谢您的编辑,但这是所有三个 api 的常见错误处理程序。对于第一种情况,我需要以不同方式处理,接下来的两种情况应该以不同方式处理:/
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-09
  • 1970-01-01
  • 2011-05-13
  • 2019-04-13
  • 2017-09-23
相关资源
最近更新 更多