I'm making an Angular 2 HTTP get request and in return I get
Observable<Message[]>
I want to transform this observable into multiple emit.
So let's say the server returned Message array with length 3.
I would like to get 3 notification in my subscribe call (on for each value in the array) instead of getting one call with the array.
e.g : ['Hello','Hey','Howdy'] - > 'Hello', 'Hey','Howdy'
I found an operator that does transform the array (Observable.for), but this operator takes as an argument an array and not an Observable.
Subscriptions to observables are quite similar to calling a function. But where observables are different is in their ability to return multiple values called streams (a stream is a sequence of data over time). Observables not only able to return a value synchronously, but also asynchronously.
RxJS switchMap() operator is a transformation operator that applies a project function on each source value of an Observable, which is later merged in the output Observable, and the value given is the most recent projected Observable.
RxJS map() operator is a transformation operator used to transform the items emitted by an Observable by applying a function to each item. It applies a given project function to each value emitted by the source Observable and then emits the resulting values as an Observable.
You can use the concatAll
operator to flatten the array (mergeAll
will work as well).
Observable.of(['Hello','Hey','Howdy'])
.concatAll()
.subscribe(console.log)
See demo: https://jsbin.com/gaxajex/3/edit?js,console
Try this:
Observable.from(yourRequest())
.flatMap(msgList => Observable.from(msgList))
.subscribe(msg => console.log(msg));
yourRequest()
in this case should return array.
If yourRequest()
returns Observable
then:
yourRequest().flatMap(msgList => Observable.from(msgList))
.subscribe()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With