Marinho Brandão Marinho Brandão - 1 year ago 209
TypeScript Question

Observable from an array doesn't work in TypeScript

I'm trying to create an observable from an array, as documentation says in

import {Observable} from 'rxjs/Observable';
let theList = Observable.from(sites);

but I get:

TypeError: Observable_1.Observable.from is not a function

my goal is to use operators like
over a Observable sequence, as a standard
seems to not support, as below:

this.theList = new Observable(observer => {
// this works;

this.sub = this.theList.reduce(function() {
// this is never called
return acc;
}).subscribe(l => {
// this is never called
this.finalList = l;

The code can be found in this Plnkr: (


Answer Source

There is multiple solutions :

1 - Import specific element

In your example, you are just importing the Observable, however, you use the .from() method in order to create an observable from an array. So you have to import the .from() method if you want to use it. That is the same for the reduce operator.

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/from';
import 'rxjs/add/operator/reduce';

2 - Import all operator and method

Observable is being brought in from rxjs/Rx, so pulling it in this way will automatically get you all of the operators and method.

import { Observable } from 'rxjs/Rx';

What is the difference ?

The big difference between these two approach is that you will not import all operators at once by using the first approach. It can be useful when you're working in production mode.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download