Creating and returning Observable from Angular 2 Service

2,364 views
Skip to first unread message

JG

unread,
Nov 12, 2015, 11:09:19 AM11/12/15
to AngularJS

I posted this on Stack Overflow, but I am not sure that I tagged it correctly. Sorry if this is a duplicate.



This is more of a "best practices" question. There are three players: a Component a Service and a Model. The Component is calling the Service to get data from a database. The Service is using

this.people = http.get('api/people.json').map(res => res.json());

to return an Observable.

The Component could just subscribe to the Observable:

    peopleService.people
        .subscribe(people => this.people = people);
      }

But what I really want is for the Service to return an Array of Model objects that was created from the data that the Service retrieved from the database. I realize that the Component could just create this array in the subscribe method, but I think it would be cleaner if the service do that and make it available to the Component. How can the Service create a new Observable, containing that array, and return that?

JG

unread,
Nov 12, 2015, 2:14:27 PM11/12/15
to AngularJS
I came up with a working solution, but I wonder if this is a correct solution. I have the Service build an Array of Models and return a Promise<Array<Model>>. Still wonder if this it the appropriate way of implementing a DAO.

Cory Rylan

unread,
Nov 24, 2015, 5:49:48 PM11/24/15
to AngularJS
I wrote a blog post on how I have been using Observables in my data services in Angular 2. Maybe this will help.  http://coryrylan.com/blog/angular-2-observable-data-services
Reply all
Reply to author
Forward
0 new messages