angular – 如何从Observable.from中收集发射值数组?
发布时间:2020-12-17 18:02:23 所属栏目:安全 来源:网络整理
导读:所以在Rxjs中,我有很多代码, return Observable.from(input_array) .concatMap((item)={ //this part emits an Observable.ofstring for each item in the input_array }) .scan((output_array:string[],each_item_output_array:string)={ return output_arr
所以在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中的代码,所以我想知道如何从运算符中收集observable中每个项的输出数组? 解决方法
在您对
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","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",value) => [...acc,value],[]) .subscribe(value => console.log(JSON.stringify(value))); <script src="https://unpkg.com/rxjs@5/bundles/Rx.min.js"></script> 请注意,扫描会为其接收的每个值发出一个数组.如果您只想在observable完成时发出一个数组,则可以使用toArray运算符: Rx.Observable .from(["a","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> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |