user3471528 user3471528 - 1 year ago 87
TypeScript Question

create Observable<T> from result

I'm trying Angular2.

I noticed that the http service use Obserable object instead of Promise (I don't like much that choice.. asyc/await are arriving)

In my service I download a list of Plants from the webservice. Clicking on a plant I show the details using the routing.
But in this way when I go back, the plants are downloaded again (becouse the constructor is called again).

To avoid this I want to do something like:

public getPlants():Observable<Plants[]>
if (this._plants != null)
return Observable.fromResult (this._plants); //This method does not exists

return this._http.get('../../res/heroes.json')...

Is there a way to do that?
How can I import the Observable class in my ts file?


Answer Source

This is my working solution:

if (this._heroes != null && this._heroes !== undefined) {
    return Observable.create(observer => {;

I hope that this is the best solution.

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