Reputation: 1931
In my Angular 2 application, i'am trying to implement ngrx, so i have in one of my component this code :
OnInit() {
this.myService.getApplicationList();
}
That service return a this json :
{
Count : 25, // count of all applications
Applications[Array] // array with applications objects in it
Categories[Array] // array of categories
}
How can assign count, Applications and categories to their respective reducer with only one request made ?
What i'am doing now is mapping the response object to response.json().Applications then.
Myservice.ts
getApplicationList(limit: number) {
return this.http.get(this.baseUrl)
.map(res => res.json().Applications )
.map(payload => ({ type: 'GET_APP', payload : payload }))
.subscribe(action => {
this.store.dispatch(action)});
}
And for getting the categories i'am doing the same previous request :
getApplicationList(limit: number) {
return this.http.get(this.baseUrl)
.map(res => res.json().Categories)
.map(payload => ({ type: 'GET_CATEGORIES', payload : payload }))
.subscribe(action => {
this.store.dispatch(action)});
}
How can i simplify this repetition and map both my Applicaitons and Categories arrays with only one http requets ?
Upvotes: 1
Views: 1338
Reputation: 61
I think that a more correct way to do this would be to utilize an ngrx @Effect (https://github.com/ngrx/effects);
Upvotes: 1
Reputation: 7060
You can handle both in the subscription function.
getApplicationList(limit: number) {
return this.http.get(this.baseUrl)
.map(res => res.json())
.subscribe(res => {
this.store.dispatch({ type: 'GET_CATEGORIES', payload : res.Categories });
this.store.dispatch({ type: 'GET_APP', payload : res.Applications });
});
}
Upvotes: 1