TKDev
TKDev

Reputation: 503

angular 4 sequential async http requests with cancellation on error response

I'm trying to make 3 sequential & async (none parallel), requests with HttpClient and Observable.forkJoin.

So far this is how it looks, first the fileOperations array:

requestPayloadObjects:any[];//array of objects sent to the same request 

//... after the array was built
this.requestPayloadObjects.forEach( ( payloadObject:any,i:number )=> {
   //_uploadApi.postDoc returns an http observable
   fileOperations.push( this._uploadApi.postDoc( payloadObject ) );
});

Then after I have an array of observable I use Observable.forkJoin

// parallel subscriptions, all 3 observables are subscribed to asyncly
Observable.forkJoin(fileOperations).subscribe((res:any)=> {
        // If all http calls succeeded you get here
    },(err:any)=> {
        // If 1 of all 3 that were sent failed you get here
    });    

However what I want is:

// NONE-parallel subscription  
Observable.forkJoin(fileOperations).subscribe((res:any)=> {
        // If all http calls succeeded you get here
    },(err:any)=> {
        // If 1 failed, you get here, but you do not send the others
    });    

I'm sure Observable.forkJoin is not the Observable method to achieve this, but what is? How do I make none parallel subscriptions, which continue to the next one only if the previous succeeded? What is the propper way to do this using Observables?

Upvotes: 1

Views: 369

Answers (2)

TKDev
TKDev

Reputation: 503

Using Observable.concat as @MichaelKie suggested, I managed to resolve this the following way.

let requestPayloadObjects:any[] = [{...},{...},{...}];
let firstServerCall:Observable<any>; 

this.requestPayloadObjects.forEach( ( payloadObject:any,i:number )=> {
        let observable = this._uploadApi.postDoc(payloadObject:any);
        if(i===0) {
            firstServerCall = observable ;
        }
        else {
            firstServerCall = firstServerCall.concat(observable );
        };
});
firstServerCall.subscribe((res:any)=> {
  // 1. will get here after every successful response
  // 2. will continue on to send next http call after this
},(err:any)=> {
  // will get here if subscription fails, without continuing to the next observable.
})

Upvotes: 1

MichaelKie
MichaelKie

Reputation: 146

I think concatAll is what you are looking for. Check out the rxjs documentation for it.

Upvotes: 2

Related Questions