1

Let's say I have 4 API calls. In this case, each of the 4 calls return the same data structure so I don't need to manipulate the return types. They each return an array of objects. I'd like to call them all, but combine them into on output array. I tried combining forkJoin with .concat() but that didn't do what I expected (it put them inside of smaller arrays).

forkJoin([
  this.service.getData('something', 'somethingelse'),
  this.service.getData('something1', 'somethingelse2')
].concat()).subscribe(data => console.log(data))
3
  • Let me check if I understand... each call gives you something like [{a:1 b:1}, {a:2,b:2}] and [{a:3 b:3}, {a:4,b:4}]... and you want [{a:1 b:1}, {a:2,b:2}, {a:3 b:3}, {a:4,b:4}] as the final output? Commented Dec 17, 2020 at 23:17
  • yes. One array that takes all the objects of every inner array and puts them into a singular array output. I can use forkJoin with the dictionary syntax and convert each return Object to an array, but that seems unnecessary given all RxJs can do. I just don't know which operator to use in which succession. Commented Dec 17, 2020 at 23:25
  • Well.. what if you just do this: forkJoin([ this.service.getData('something', 'somethingelse'), this.service.getData('something1', 'somethingelse2') ]).subscribe(data => console.log(data[0].concat(data[1]))) Commented Dec 17, 2020 at 23:29

1 Answer 1

3

Consider the following implementation: (concating the arrays is performed once data has been returned)

forkJoin([
  this.service.getData('something', 'somethingelse'),
  this.service.getData('something1', 'somethingelse2')
])
.pipe(
  map(x => x.reduce((arr, curr) => [...arr,...curr]))
)
.subscribe(data => console.log(data))

Or using ES2019 flat

forkJoin([
  this.service.getData('something', 'somethingelse'),
  this.service.getData('something1', 'somethingelse2')
])
.pipe(
  map(x => x.flat())
)
.subscribe(data => console.log(data))
Sign up to request clarification or add additional context in comments.

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.