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..
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 :
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)
上一篇: 在guzzle 6中初始化后设置请求选项
下一篇: 如何在Angular2中管理服务