How to manage services in Angular2

Angular 2 : 2.0.0-alpha.31 / Typescript 1.5

I currently manage my service as a simple Class , then I insert this Class into another component. Example:

 export class PlayerService { http: Http; players = []; constructor( @Inject(Http) http) { this.http = http; } getAll(callback) { this.http.get('/data/players.json') .toRx() .map((res) => res.json()) .subscribe((data) => { this.players= data; callback(data); }); } add(player) { //call webservice to save user this.players.push(player); //only if save has work } delete(player) { //Not implemented yet } get(id) { //Not implemented yet } } 

I think I am doing it wrong.

  • Am I using http.get().toRx().subscribe() ? I thought I saw some people return Observable directly from toRx()
  • If two components request players ( getAll() ) at the same time, two requests will be executed. Do I need to control the flag or is there another way?
  • I work here with a callback. What do I need to do if I want the data "immediately" (without async)
  • Will components automatically be added to add / remove players? Should I use some kind of event to handle this (any example?)

So my question is:

  • Is there a general way to manage services in Angular2 ?
+7
javascript angular typescript
source share
1 answer

First of all, the service is well executed, as you did, and this is the way to go with Angular2: A Class introduced in other components.

However, about the other issues you are raising, I would rather go back and keep the result in a promise instead of using a callback:

 getAll() { return players || players = new Promise( (resolve) => this.http.get('people.json').observer({next: resolve}) ); } 

Note You can use Observable.toPromise (), but for some reason it doesn't work for me in Angular2

Thus, further calls to getAll () will not trigger more responses.

For synchronous questions you should not do this. Now that you have this in the promise, just call getAll () and return the promise when the player requests.

 get(id) { return getAll().then((result) => {return Promise.resolve(result[id])}); } 

About how to handle additions and deletions of players, exactly what Observables is for RxJS. You also need to provide an observable stream that notifies it of observers when changing the list of players. You can use EventEmitter to do this:

 constructor( @Inject(Http) http) { this.http = http; this.myEventEmitter = new EventEmitter(); } getUpdateStream() { myEventEmitter.toRx(); } 

When you change the list of players, just myEventEmitter.next(players)

+4
source share

All Articles