代码之家  ›  专栏  ›  技术社区  ›  merko

NGRX状态属性消失

  •  0
  • merko  · 技术社区  · 6 年前

    我正在尝试从数据库中获取用户信息。在组件中,我从服务中获取解码的id,然后调用将id作为参数的操作。它返回用户,在网络标签中有响应。状态属性“currentUser”一直为null,直到它应该更改为response,然后它就会消失。

    export interface State {
      loading: boolean;
      loggedIn: boolean;
      currentUser: User;
    }
    
    const initialState: State = {
      loading: false,
      currentUser: null,
      loggedIn: localStorage.getItem("token") ? true : false
    };
    case AuthActions.GET_USER_SUCCESS:
      {
        return {
          ...state,
          loading: false,
          loggedIn: true,
          currentUser: action.user
        };
      }
    
      @Effect()
      getUserInfo$: Observable < Action > = this.actions$
        .ofType(fromActions.GET_USER)
        .pipe(map((action: fromActions.GetUser) => action.id),
          concatMap(id => {
            return this.authService.getUser(id);
          })
        )
        .pipe(map((res: User) => ({
          type: fromActions.GET_USER_SUCCESS,
          payload: res
        })));
      }
    2 回复  |  直到 6 年前
        1
  •  0
  •   kauppfbi    6 年前

    试着这样做:

       
    
    @Effect()
      getUserInfo$: Observable<Action> = this.actions$
        .ofType(fromActions.GET_USER)
        .pipe(
          map((action: fromActions.GetUser) => action.id),
          concatMap(id =>
            this.authService.getUser(id).pipe(
              map((res: User) => ({
                type: fromActions.GET_USER_SUCCESS,
                payload: res
              }))
            )
          )
        );
        2
  •  0
  •   Heehaaw    6 年前

    {
      type: fromActions.GET_USER_SUCCESS,
      payload: res
    }
    

    但是在你的减速机里你希望它有一个 user 它的属性

    case AuthActions.GET_USER_SUCCESS:
    {
      return {
        ...state,
        loading: false,
        loggedIn: true,
        currentUser: action.user // <- try action.payload or action.payload.user, 
                                 // depending on what you get from the API
      };
    }
    

    另外,试着把你的效果塑造成这样:

    @Effect()
      getUserInfo$: Observable <Action> = this.actions$
        .ofType(fromActions.GET_USER)
        .pipe(
          switchMap(({ id }) => this.authService.getUser(id)
            .pipe(
              map((res: User) => ({ type: fromActions.GET_USER_SUCCESS, payload: res }),
              // Handling errors in an inner Observable will not terminate your Effect observable 
              // when there actually is an error
              catchError(err => ({ type: fromActions.GET_USER_ERROR, payload: err })
            )
          )         
        );