Search code examples
angularerror-handlingrxjsfork-join

How to ignore an error after catching it and execute final result in rxjs forkJoin?


   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 ??     

          }    
     );
}

How can i ignore the error which i catch in service2.fn2() and service3.fn3() and execute the final part?

I'm new to this and any help would be appreciated.

I saw this link but i didn't understand completely. If anyone can tell in simple terms it would be great.

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


Solution

  • the subscription method accept 3 functions parameters as you can see in his implementation

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

    use the second one to handle your error

    UPDATED

    your function will look like

    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
          }    
     );
    }
    

    the second function will be executed if a error is throw

    UDPATED #2

    if you want to handle the errors independently you can catch each one

           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*/)) 
    

    notice you will receive undefined on the subscription array for each observable that fails