angular - 如何从 Observable.from 收集发射值数组?

标签 angular asynchronous rxjs reactive-programming observable

所以在 Rxjs 中,我有一堆代码,

return Observable.from(input_array)
           .concatMap((item)=>{
               //this part emits an Observable.of<string> for each item in the input_array
           })
           .scan((output_array:string[],each_item_output_array:string)=>{
               return output_array.push(each_item_output_array) ;
           });

但显然这是错误的,扫描会破坏 concatMap 内部的代码,所以我想知道如何收集可观察的 from 运算符中每个项目的输出数组?

最佳答案

在您调用 scan 时您没有为累加器指定种子。在这种情况下,第一个值用作种子。例如:

Rx.Observable
  .from(["a", "b", "c"])
  .scan((acc, value) => acc + value)
  .subscribe(value => console.log(value));
<script src="https://unpkg.com/rxjs@5/bundles/Rx.min.js"></script>

在您的代码段中,第一个值不是数组,因此您不能对其调用 push。要将值累积到一个数组中,您可以像这样指定一个数组种子:

Rx.Observable
  .from(["a", "b", "c"])
  .concatMap(value => Rx.Observable.of(value))
  .scan((acc, value) => {
    acc.push(value);
    return acc;
  }, []) // Note that an empty array is use as the seed
  .subscribe(value => console.log(JSON.stringify(value)));
<script src="https://unpkg.com/rxjs@5/bundles/Rx.min.js"></script>

虽然,对于某些用例,最好不要改变数组:

Rx.Observable
  .from(["a", "b", "c"])
  .concatMap(value => Rx.Observable.of(value))
  .scan((acc, value) => [...acc, value], [])
  .subscribe(value => console.log(JSON.stringify(value)));
<script src="https://unpkg.com/rxjs@5/bundles/Rx.min.js"></script>

请注意,scan 为它接收到的每个值发出一个数组。如果您只想在可观察对象完成时发出单个数组,则可以改用 toArray 运算符:

Rx.Observable
  .from(["a", "b", "c"])
  .concatMap(value => Rx.Observable.of(value))
  .toArray()
  .subscribe(value => console.log(JSON.stringify(value)));
<script src="https://unpkg.com/rxjs@5/bundles/Rx.min.js"></script>

关于angular - 如何从 Observable.from 收集发射值数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42311674/

相关文章:

javascript - Promise .then() 链 : second . 然后在第一个之前运行? 0.0

angular - Ionic : this. http.get(...).map 不是函数

angular - 如何在 Angular 中顺序发送多个 Http 请求

angular - Webpack 包分析器 "+ n Modules"

java - 非阻塞风格有什么好处?

java - 创建代理对象以异步调用目标方法(拆分逻辑/渲染线程)

rxjs - API 返回一个我需要解析的数组;每个项目一个请求

javascript - 包含 `declare module ' graphql/error/GraphQLError' 的声明 (.d.ts) 文件;在 Angular 项目中的 index.d.ts 中

angular - 使用 Auth0 获取 "Callback URL mismatch"

angular - fxFlex 不调整元素大小