管道一个 observable 以使用 api 的结果更新项目列表

Pipe an observable to update list of items with result from api

我有一个 observable 可以抽取一个项目列表。我需要 pipe observable 以便每个项目都会执行 api 调用,使用 api 调用的结果更新自身并最终提供更新的来自可观察对象的项目列表。

我可以使用哪种 rxjs 运算符来执行此操作?

如果您可以按顺序执行此操作,则可以尝试这样的操作

const items$ = from([{id: 1, name: 'a'}, {id: 2, name: 'b'}, {id: 3, name: 'c'}])

const request = async (data) => {
  // data here would be any single object in your array
  // and `doHttpRequest` is any function that returns the type
  // given the original object
  const type = await doHttpRequest(data)
  return {
    ...data,
    type
  }
}

const results$ = items$.pipe(
  // flatMap being used here since we're not returning
  // a synchronous value from request
  flatMap(request),
  toArray()
);

// somewhere else in your code
results$.subscribe(value => console.log(value));

如果省略 toArray 部分,您可以将可观察对象保留为对象流,而不是最后完成的单个数组。