19
votes

I currently have a problem with Angular2 and Observable object.

I have a Component who calls a Service : a real one linked to an api and a fake one.

The service linked to the API works well but when I use the fake one, I want to return an Array from Observable object but I have this error :"Observable_1.Observable.fromArray is not a function"

Here is my code :

Component :

this._raceService.list().subscribe(newRaces => { 

  this.races = newRaces;
}); 

Real Service :

list(){ return this._http.get('http://dev.backend.com/api.php', options).map(res => res.json()); }

Fake service :

list() { return Observable.fromArray([{ name: 'London' }]); }

Can you help me plz ?

Cheers

7

7 Answers

26
votes

should that be...

Rx.Observable.from(yourarray)

fromArray seems to be deprecated

16
votes

Answer needs to be updated for RxJS 6, it is now

import {from} from 'rxjs';

const observable = from([ { a: 1, b: 2 } ]);
14
votes

Observable.fromArray() was removed in RxJS version 5, use from()

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/from';
...
Observable.from([1, 2, 3, 4]);
4
votes

I had the same problem and had to add this import statement in my component:

import 'rxjs/add/observable/fromArray';

I found the import to add by searching for fromArray in the Rx.js file I was referencing (be careful since there may be different versions of the file in your project):

System.register("rxjs/add/observable/fromArray", ["rxjs/Observable", "rxjs/observable/ArrayObservable"], true, function(require, exports, module) {
  // ...
});
4
votes

I had the same problem, after some research in my code ...

I imported:

import {Observable} from "rxjs/Observable";

Instead of:

import {Observable} from "rxjs/Rx";

Hope it can help someone else.

4
votes

I had the same issue. I believe you may be getting this because fromArray has been deprecated.

import rxjs/Observable to prevent importing other parts of rxjs you don't need

import { Observable } from 'rxjs/Observable';

fromArray has been deprecated. Instead use

list() { return Observable.from([{ name: 'London' }]); }
1
votes

try this:

import { from } from 'rxjs/observable/from';

const promiseSource = from(new Promise(resolve => resolve('Hello World!'))); 

https://learnrxjs.io/operators/creation/from.html