简体   繁体   English

您如何根据可观察 RxJ 的响应修改数组中的对象

[英]How do you modify object in array with response from observable RxJs

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.我正在尝试遍历一组人并调用一个返回一个新年龄的 api,我将覆盖该年龄,然后与 dog 数组合并。 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 .这总是返回一个空的modifiedPeople How can I perform this operation with RxJs in ES6如何在 ES6 中使用 RxJs 执行此操作

You cant call the async call in the Array.map as it is a synchronous method.您不能在Array.map调用异步调用,因为它是一种同步方法。 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.它不会等待异步调用完成并进一步移动,这就是为什么您对modifiedPeople未定义,而且pipe运算符返回一个需要订阅结果的Observable

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

the result will be your modifiedPeople结果将是您的modifiedPeople

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM