0

I am trying to iterate over an array of people and call an api which returns a new age which I will override the age and then merge with dogs array. The code looks like this:

const dogs = [{name:'Chichi', age:2}, {name:'Yayo', age:4}];
const people = [{name:'Mike', age:23}, {name:'John', age:45}];

const modifiedPeople = people.map(person => {        
    getNewAge(person).pipe(map(newAge=> {return person.age = newAge}));

return [...dogs, modifiedPeople];

})

This always returns an empty modifiedPeople. How can I perform this operation with RxJs in ES6

1 Answer 1

3

You cant call the async call in the Array.map as it is a synchronous method. It will not wait for async call to complete and moves further which is why you are getting undefined for modifiedPeople and moreover pipe operator returns an Observable which needs to be subscribed for the result.

forkJoin(
  people.map(person =>
    this.getNewAge(person)
      .pipe(map(newAge => ({ ...person, age: newAge })))
  )
)
.subscribe(result => console.log(result));

the result will be your modifiedPeople

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.