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..
http.get().toRx().subscribe()
? I thought I saw that some people return the Observable
directly from toRx()
getAll()
) at the same time, two queries will be executed. Do I have to manage flag or is there another way ?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 :
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).
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With