Reputation: 10838
I have this rxjs code:
private getString(): Observable<string> {
return from(randomString());
}
private transformString(text: string): Observable<string> {
let newString = text.split("").reverse().join("");
console.log(newString); <--- all looking good, getting a single string
return from(newString);
}
public getString(): Observable<any> {
return this.randomString().pipe(
switchMap((myString) => this.transformString(myString))
);
}
However there is an issue when I am when receiving the final result in subscription, it is producing a string array of my new string
getString().subscribe(str => {
console.log(str) <--- prints an array but I am expecting to get just one single reversed string
});
Can you explain why it is happens and how to fix?
Upvotes: 0
Views: 832
Reputation: 152
As of with the rxjs operators, it will emit the transformed value as an observable. So there is no need to create an observable explicitly for the transformed value.
Kindly change the transformString function as below if your intent is to get the transformed string on subscribing it.
private transformString(text: string): string {
let newString = text.split("").reverse().join("");
console.log(newString);
return newString;
}
Upvotes: 0
Reputation: 3664
from
doesn't interpret the argument to create an observable as you'd expect.
Specifically, note the explanation from the linked documentation:
A String, in this context, is treated as an array of characters.
If you want to get your snippet working using from
specfically, you'll need to enclose the argument with square brackets. That is:
return from([newString]);
And below is just a demo of the difference between from
and of
usage:
const { from, of } = rxjs;
// 'h', 'e', 'l', 'l', 'o'
from('hello').subscribe(console.log);
// 'hello'
of('hello').subscribe(console.log);
// 'hello'
from(['hello']).subscribe(console.log);
<script src="https://unpkg.com/[email protected]/bundles/rxjs.umd.min.js"></script>
Upvotes: 2
Reputation: 612
Since the string has to be returned as an Observable, using the of method of the Observable class should work
import { Observable } from 'rxjs/Observable';
return Observable.of(newString)
Upvotes: 1