6

I am able to create observable from an array but its type is Observable<number> not Observable<number[]>

getUsers(ids: string[]): Observable<number[]> {
   const arraySource = Observable.from([1, 2, 3, 4, 5]);
   //output: 1,2,3,4,5
   const subscribe = arraySource.subscribe(val => console.log(val));

   let returnObserable = Observable.from([1, 2, 3, 4, 5]);
   return returnObserable; //error at this line, because of the return type
}

Is there any other way to create observable other than from ?

1 Answer 1

5

If you want the entire array to be emitted as a single emissions use Observable.of instead:

const arraySource = Observable.of([1, 2, 3, 4, 5]);

Observable.from iterates the array and emits each item separately while Observable.of takes it as without any further logic.

Alternatively, you could also nest two arrays but that's probably too confusing:

const arraySource = Observable.from([[1, 2, 3, 4, 5]]);
Sign up to request clarification or add additional context in comments.

3 Comments

Observable.of([1, 2, 3, 4, 5]) this worked, then what is the use of Observable.of([[1, 2, 3, 4, 5]]) ?
Sorry, my bad! I wanted to write Observable.from([[1, 2, 3, 4, 5]])
@martin .. sorry for late comment..had one doubt...when using .of([1, 2, 3, 4, 5]) and binding to HTML using async pipe works well. However using .from([1, 2, 3, 4, 5]) and binding with async pipe gives an error .. I am wondering why so ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.