web-dev-qa-db-fra.com

ngrx 8 effectue une action de répartition d'un autre type

Je vous parviens ici à propos des effets ngrx, ce que j'essaie de faire, c'est d'avoir une connexion de fonction qui distribue une connexion de type action et un effet sur cette action utilisera mon service pour effectuer un appel api. Après ce jeton de retour, je veux envoyer deux autres actions, l'une de type getUserMenu et l'autre de type getUserInfo. Ces deux actions seront de type différent et auront un effet différent.

J'ai 3 magasins à la fin: un pour le jeton et auth un pour les informations utilisateur un pour les informations de menu

j'ai essayé des choses comme ça:

login = createEffect(
  () =>
  this.actions$
  .pipe(
  ofType(authLogin),
    tap(action => {
    console.log("EFFECT LOGINNNN");
    return this.authService.postLogin(action.username, 
      action.password).pipe(
        map((data: any) => {
          console.log("AUTHTHHTHTH DATATA ", data);
          let props = data.token;
          let payload = {
            token: data.token,
            isAuthenticated: true
          }
      this.store.dispatch(moMenuHttpGetListAction({US_ID: action.username}));  
      this.store.dispatch(userHttpGetInfoAction({US_ID:action.username}));
      this.localStorageService.setItem(AUTH_KEY, payload);
    }))
  })
),
{ dispatch: true }
);

si je mets en place un travail de fausse connexion mais qu'aucune méthode n'est appelée pour obtenir les informations utilisateur et le menu utilisateur, mais lorsque je mets la commande true, j'ai une boucle infinie sur ce même effet, l'action moMenuHttpGetListAction ressemblerait à ça:

moMenuHttpGetListEffect = createEffect(
     () => this.actions$.pipe(
        ofType(moMenuHttpGetListAction),
        switchMap(action => {
          console.log("MOMENU LOGINNNN");

          return this.moMenuService.getKmApplications(action.US_ID).pipe(
          map((data: any) => {
            console.log("MOMENU DATATA ", data);
            console.log("MOMENU DATATA ", action.US_ID);
            let payload = {
              MO_MENU: data
            }

          this.store.dispatch(moMenuSetListAction({payload: data}));
           this.localStorageService.setItem(MENU_KEY, payload);
          }))
        })
        ),
    { dispatch: false }
  );

mais sur celui-ci, lorsque j'ai défini la répartition sur true, j'ai eu une erreur de compilation. et mon action ressemble à:

import { createAction } from "@ngrx/store";
import { props } from "@ngrx/store";
import { MoMenu, MoMenuState } from "./mo_menu.models";

//TODO CHANGER ME_ID en US_ID
export const moMenuGetErrorAction = createAction("[User] Get Info");
export const moMenuGetIsLoadingAction = createAction("[User] Get Info");

export const moMenuSetErrorAction = createAction('[MoMenu] HTTP GET ACTION',
    props<{error: string}>()
    );
export const moMenuSetLoadingAction = createAction('[MoMenu] HTTP GET ACTION',
    props<{loading: boolean}>()
    );
export const moMenuHttpGetListAction = createAction('[MoMenu] HTTP GETLIST  ACTION',
    props<{US_ID: string}>()
    );
export const moMenuHttpGetListErrorAction = createAction('[MoMenu] HTTP GET ACTION Error',
    props<{error: any}>()
    );

export const moMenuGetListAction = createAction("[MoMenu] Get List");
export const moMenuSetListAction = createAction("[MoMenu] Set Mo Menu List",
    props<{payload: MoMenu[]}>());
export const moMenuDeleteAction = createAction("[MoMenu] Delete List");

ce sont les deux réducteurs concernés car quelqu'un me demande d'ajouter:

Ngrx est un peu nouveau pour moi, donc j'aimerais de l'aide à ce sujet =)

import { AuthState } from './auth.models';
import { authLogin, 
  authLogout ,
  authGetErrorAction,
  authGetIsLoadingAction,
  authSetErrorAction,
  authSetIsLoadingAction
} from './auth.actions';
import { createReducer, on, Action } from '@ngrx/store';

export const initialState: AuthState = {
  isAuthenticated: false,
  token: undefined,
  isLoading: false,
  HttpResponse: undefined
};

const reducer = createReducer(
  initialState,
    on(authSetErrorAction,  (state, { error }) => ({
    ...state, HttpResponse:  error
  })),
   on(authSetIsLoadingAction,  (state, { isLoading }) => ({
    ...state, isLoading: isLoading 
  })),

  on(authLogin, state => ({ ...state, isAuthenticated: true })),
  on(authLogout, state => ({ ...state, isAuthenticated: false }))
);

export function authReducer(
  state: AuthState | undefined,
  action: Action
): AuthState {
  return reducer(state, action);
}

import { MoMenuState } from "./mo_menu.models";
import { 
  moMenuGetListAction, 
  moMenuDeleteAction,
  moMenuHttpGetListAction,
  moMenuSetListAction,
  moMenuHttpGetListErrorAction,

  moMenuGetErrorAction,
  moMenuGetIsLoadingAction,
  moMenuSetErrorAction,
  moMenuSetLoadingAction
 } from "./mo_menu.actions";
import { createReducer, on, Action } from "@ngrx/store";

export const initialState: MoMenuState = {
    isLoading: false,
  HttpResponse: undefined,
MoMenuItems: null
}

const reducer = createReducer(
  initialState,
  on(moMenuSetErrorAction,  (state, { error }) => ({
    ...state, HttpResponse:  error
  })),
   on(moMenuSetLoadingAction,  (state, { loading }) => ({
    ...state, isLoading: loading 
  })),

  on(moMenuHttpGetListErrorAction, (state, { error }) => (
    undefined)),
   on(moMenuSetListAction, (state, { payload }) => ({
    ...state, MoMenus: payload 
  })),

 on(moMenuHttpGetListAction, (state, { US_ID }) => ({
    ...state
  })),
  on(moMenuGetListAction, state => state),
  on(moMenuDeleteAction, state => state)
);

export function moMenuReducer(
  state: MoMenuState | undefined,
  action: Action
): MoMenuState {
  return reducer(state, action);
}

Si certains d'entre vous ont une idée pour moi?

3
Razgort

Vous pouvez faire comme ça pour envoyer plusieurs actions dans votre effet

@Effect()
    someEffect$: Observable<Action> = this.actions$.pipe(
        ofType<SOME_ACTION>(SOME_ACTION),
        switchMap(_ =>
            of(
                new myAction.Refresh(),
                new myAction.Clear()
                // another action
            )
        )
    );

Assurez-vous également d'avoir un effet approprié qui écoute votre action pour la faire fonctionner

0
Tony Ngo