I am playing around with RXJS for TypeScript and stumbled upon an issue that I cannot explain myself. I have an observable
that emits multiple strings. I then want to apply switchMap
to it which is supposed to prepend "a" to each of those strings:
var o = Observable.create((observer) => {
observer.next("hi")
observer.next("bla")
})
o.switchMap(str => "a" + str).subscribe(str => console.log(str))
My expected output:
ahi
abla
Actual output:
a
h
i
a
b
l
a
So somewhere between switchMap and subscribe, the string gets broken down into characters apparently.
Can someone explain why this happens?
I guess you meant to use map
instead of switchMap
.
switchMap
actually expects an ObservableInput
as return-value, which in your case is a string, which in turn is treated as an array and therefore split up into single elements.
To have your expected result with switchMap
you could do:
o.switchMap(str => Observable.of("a" + str))
.subscribe(str => console.log(str));
But better use:
o.map(str => "a" + str)
.subscribe(str => console.log(str))
New syntax with pipe:
o.pipe(
map(str => "a" + str)
).subscribe(str => console.log(str))
I think you need map
instead of switchMap
.
The function passed to switchMap
expects to return an observable or promise. "a" + str
is not.
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