2

I've seen this asked a few times but I can't work out how to implement this to solve my issue.

I've basically got an array of http calls that I need to execute in sequentially order. Specifically I need to execute one, wait for it to return then execute the next.

let requests = [
  this.http.post('http://localhost:4200/api/value', 'one'),
  this.http.post('http://localhost:4200/api/value', 'two'),
  this.http.post('http://localhost:4200/api/value', 'three'),
  this.http.post('http://localhost:4200/api/value', 'four'),
];

So I'm currently using a forkJoin but this runs the requests simultaneously which is not what I want.

forkJoin(observableBatch).subscribe(result => {
  // success
}, error => {
  // log error
}); 

I read using concatMap might be the answer but how do I use this on an array of observables?

3

2 Answers 2

5

Try with concat function of RXJS, try this

import { concat } from 'rxjs';

let requests = [
  this.http.post('http://localhost:4200/api/value', 'one'),
  this.http.post('http://localhost:4200/api/value', 'two'),
  this.http.post('http://localhost:4200/api/value', 'three'),
  this.http.post('http://localhost:4200/api/value', 'four'),
];

concat(...requests).subscribe(result => {
  // success
}, error => {
  // log error
}); 
Sign up to request clarification or add additional context in comments.

2 Comments

import { concat } from 'rxjs'. It's not an operator. And you're missing the call to subscribe.
Will the subscribe result be hit for each one of those four calls or just once all four have executed? I've a scenario where I need the response eTag to send in the header of the subsequent request
0

I think you want to use concatMap if by "sequentially" you mean the next http request doesn't request until the response is received from the previous.

let requests = [
  this.http.post('http://localhost:4200/api/value', 'one'),
  this.http.post('http://localhost:4200/api/value', 'two'),
  this.http.post('http://localhost:4200/api/value', 'three'),
];

const observer = {
  complete: () => {
    // code here for when all requests complete
  },
  error: (err: any) => {
    console.error(`error in concatMap observer`, err);
  }
};

from(requests).pipe(concatMap((request) => {
  return request;
})).subscribe(observer);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.