Nacim Idjakirene
Nacim Idjakirene

Reputation: 1931

Angular 2 ngrx : multiple reducer with one http request?

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

Answers (2)

tubbsy
tubbsy

Reputation: 61

I think that a more correct way to do this would be to utilize an ngrx @Effect (https://github.com/ngrx/effects);

  • setup a state called AppState with two properties; categories & applications.
  • create an action like 'LOAD_APP', the effect should listen for the action, then once triggered, will fire the http request and then dispatch an action called LOAD_APP_SUCCESS with the payload as the response, then store then store the payload in the Store AppState props respectively.

Upvotes: 1

j2L4e
j2L4e

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

Related Questions