有没有办法将流中的一个项目拆分成多个项目?

时间:2017-07-05 01:39:20

标签: rxjs observable reactive-programming

考虑以下流:

--'[a,b,c]'--

'[a,b,c]'是流中的一个项目。现在我正在寻找一种方法将该流映射到这个:

--'a'--'b'--'c'--

我认为在某些时候我需要使用map,因为我只知道如何拆分数组:

Observable.from(['[a,b,c]'])
    .map(i => {
        let arr = JSON.parse(i);
        //Somehow inject the arr items into the stream (instead of arr itself)
    })
    .subscribe(console.log);

我希望在控制台中看到三个单独的条目abc

1 个答案:

答案 0 :(得分:3)

只需使用mergeMap代替map



Rx.Observable
  .from(['["a", "b", "c"]'])
  .mergeMap(value => JSON.parse(value))
  .subscribe(value => console.log(value));

.as-console-wrapper { max-height: 100% !important; top: 0; }

<script src="https://unpkg.com/rxjs@5/bundles/Rx.min.js"></script>
&#13;
&#13;
&#13;

mergeMap将展平项目函数返回的数组。