Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何等待所有流结果并将最终结果作为对象返回?_Angular_Typescript_Rxjs - Fatal编程技术网

Angular 如何等待所有流结果并将最终结果作为对象返回?

Angular 如何等待所有流结果并将最终结果作为对象返回?,angular,typescript,rxjs,Angular,Typescript,Rxjs,我是rxjs新手,这是我最近遇到的一个简单问题。我正在尝试使用Promise实用程序循环数组。我的期望是等待所有流结果和流的结束,并将其作为对象返回。但是,我不知道如何组合所有流并将它们作为单个对象返回 我已经尝试过toArray,我认为这是我想要的最接近的答案,但我希望会有一些类似toArray的操作符,比如toObject。我知道有一个叫做forkJoin的操作符,但我不知道如何在我的例子中使用它 这是我的密码 const textList = [ { key: "text1ke

我是rxjs新手,这是我最近遇到的一个简单问题。我正在尝试使用Promise实用程序循环数组。我的期望是等待所有流结果和流的结束,并将其作为对象返回。但是,我不知道如何组合所有流并将它们作为单个对象返回

我已经尝试过toArray,我认为这是我想要的最接近的答案,但我希望会有一些类似toArray的操作符,比如toObject。我知道有一个叫做forkJoin的操作符,但我不知道如何在我的例子中使用它

这是我的密码

const textList = [
  {
    key: "text1key",
    label: "text1"
  },
  {
    key: "text2key",
    label: "text2"
  },
  {
    key: "text3key",
    label: "text3"
  }
];

const myPromise = (data) => new Promise((resolve, reject) => {
  resolve("translated" + data);
})

const source = from(textList).pipe(
  concatMap(textObj =>
    myPromise(textObj.label).then(result => ({ key: textObj.key, value: result }))),
  map(({ key, value }) => ({ [key]: value })),
  toArray(),  // expect to return a single object instead of array.
);

source.subscribe(finalResult => console.log("FINAL RESULT", finalResult));
希望在订阅期间获取对象,而不是数组。

您需要用户reduce,而不是map和toArray。因此,导入reduce运算符并将代码更改为以下内容:

const textList = [
  {
    key: "text1key",
    label: "text1"
  },
  {
    key: "text2key",
    label: "text2"
  },
  {
    key: "text3key",
    label: "text3"
  }
];

const myPromise = (data) => new Promise((resolve, reject) => {
  resolve("translated" + data);
})

const source = from(textList).pipe(
  concatMap(textObj =>
    myPromise(textObj.label).then(result => ({ key: textObj.key, value: result }))),
  reduce((acc, {key, value}) => {
    acc[key] = value; // add key and value into accum
    return acc;  // return accum for the next iteration
  }, {}) // set an initial value (accum) as empty object
);

source.subscribe(finalResult => console.log("FINAL RESULT", finalResult)); // { translatedtext1Key: text1, ... }
Reduce接受一个回调函数,其中累积值是第一个参数,数组项是第二个参数。这与reduce处理简单数组的方式非常相似。
您可以阅读更多信息。

可能您需要使用reduce而不是mapArtemArkhipov是的,您是对的,我没有意识到这一点,谢谢,这正是我想要的。我没有注意到rxjs操作符的减少。