How to create an Observable from static data similar to http one in Angular?
Perhaps you could try to use the of
method of the Observable
class:
import { Observable } from 'rxjs/Observable';import 'rxjs/add/observable/of';public fetchModel(uuid: string = undefined): Observable<string> { if(!uuid) { return Observable.of(new TestModel()).map(o => JSON.stringify(o)); } else { return this.http.get("http://localhost:8080/myapp/api/model/" + uuid) .map(res => res.text()); }}
As of July 2018 and the release of RxJS 6
, the new way to get an Observable from a value is to import the of
operator like so:
import { of } from 'rxjs';
and then create the observable from the value, like so:
of(someValue);
Note, that you used to have to do Observable.of(someValue)
like in the currently accepted answer. There is a good article on the other RxJS 6 changes here.
Things seem to have changed since Angular 2.0.0
import { Observable } from 'rxjs/Observable';import { Subscriber } from 'rxjs/Subscriber';// ...public fetchModel(uuid: string = undefined): Observable<string> { if(!uuid) { return new Observable<TestModel>((subscriber: Subscriber<TestModel>) => subscriber.next(new TestModel())).map(o => JSON.stringify(o)); } else { return this.http.get("http://localhost:8080/myapp/api/model/" + uuid) .map(res => res.text()); }}
The .next()
function will be called on your subscriber.