user2120188
user2120188

Reputation: 437

Angular2 / ngrx and API calls

I have been exploring ngrx (ngrx/store) lately. I have studied some classic examples on the net (a todo app). Great example. Now I am want to take it to the next level by letting my ngrx app do some API calls. Are there examples or guidelines how to setup a ngrx (redux) app to invoke and handle api calls?

It's my understanding that api calls within the context of my redux app are side-effects (functional programming paradigm). I am wondering how/where to implement API calls in a redux app.

Upvotes: 7

Views: 9140

Answers (2)

viveksharma
viveksharma

Reputation: 715

Why side effect? Because ngrx says your reducer should be pure function, you can not use API asynchronous call in reducer. What your reducer does? -> it update your state and return updated state. So how you can make API in reducer? -> To achieve this, ngrx provide effect in @ngrx/effect.

Like reducer has switch case to identified action so effect will also subscribe all action and it will listen all actions.

How Effect will identified action? -->

like in reducer -

export function reducer(state = initialState, action: myActions.Actions) {
  switch (action.type) {    
    case myActions.actionType.SEND_CANDIDATE_OTP: {      
      return Object.assign({}, state, {otp:'test'});
    }
}

Effect will look like ->

    export class CandidateEffect {
      @Effect()
      sendCandidateOTP$: Observable<Action> = this.action$
        .ofType(myActions.actionType.SEND_CANDIDATE_OTP)
        .pipe(
          switchMap((action: myActions.GetCandidateAction) => {
            const input: myModel.GetCandidateInput = action.payload;
            return this.candidateService.SendCandidateOTP(input).pipe(
              map(resp => {
                return new myActions.SendCandidateOTPSuccessAction(resp);
              }),
              catchError((err, caught) => {
                return of(new myActions.SendCandidateOTPFailAction(err));
              })
            );
          })
        );
}

In the above piece of code you will identified action using typeOf keyword from ngrx.

Upvotes: 1

Stav Alfi
Stav Alfi

Reputation: 13943

Ngrx has its own library for side-effects ngrx/effects Some more information:

  1. Introduction: https://github.com/ngrx/effects/blob/master/docs/intro.md
  2. tutorial: https://stackoverflow.com/a/39626187/806963

There are not much resource about this library. You can find more here:

  1. https://gitter.im/ngrx/store?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge

Upvotes: 10

Related Questions