Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage Services in Angular2?

Angular 2 : 2.0.0-alpha.31 / Typescript 1.5

Currently I manage my service as a simple Class, then I inject this Class into an other 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'm doing it the wrong way..

  • I'm using http.get().toRx().subscribe() ? I thought I saw that some people return the Observable directly from toRx()
  • If two components ask for players (getAll()) at the same time, two queries will be executed. Do I have to manage flag or is there another way ?
  • I'm working here with a callback. What do I have to do if I want the data "immediately" (no async)
  • Will components be automatically informed about players add/remove ? Do I have to use some kind of event to handle this (any example?) ?

So my question is :

  • Is there a common way to manage Services in Angular2 ?
like image 771
plone1 Avatar asked Jul 25 '15 09:07

plone1


People also ask

What are services in Angular 2?

Services in Angular 2 are JavaScript functions, which are responsible for performing a single task. Services may have their associated properties and the methods, which can be included in the component. Services are injected, using DI (Dependency Injection).

What is correct for services in Angular?

Services are a set of code that can be shared by different components of an application. So for example if you had a data component that picked data from a database, you could have it as a shared service that could be used across multiple applications.


1 Answers

First of all the service is well done as you did it, and it's the way to go with Angular2: A Class injected into the other components.

That said, about the other issues you raise, I'd rather return and store 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 should be able to use Observable.toPromise() but for some reason it's not working for me in Angular2

This way further calls to getAll() will not trigger more responses.

To the synchronous questions, you should not do that. Now that you have it inside a promise, just call getAll() and return a promise when ever a player is requested.

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

About the way to handle Players additions and removals, that's exactly what Observables are meant to in RxJS. You need to provide and Observable stream that notifies it's observers when the player list changes. You can use the EventEmitter for that:

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

getUpdateStream() {
    myEventEmitter.toRx();
}

When you change the Players list just do myEventEmitter.next(players)

like image 89
Alfonso Presa Avatar answered Sep 28 '22 19:09

Alfonso Presa