【问题标题】:NGRX state property disappearsNGRX 状态属性消失
【发布时间】:2018-06-22 05:58:48
【问题描述】:

我正在尝试从数据库中获取用户信息。在组件中,我从服务中获取解码的 id,然后调用以 id 作为参数的操作。它返回用户,网络选项卡中有响应。状态属性 'currentUser' 一直为空,直到它变为响应,然后消失。

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
    })));
  }

【问题讨论】:

    标签: javascript angular ngrx ngrx-store ngrx-effects


    【解决方案1】:

    试试这样:

       
    
    @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
              }))
            )
          )
        );

    【讨论】:

    • 我应该像这样发送成功操作:return new fromActions.GetUserSuccess(res); 谢谢你的努力。 :)
    【解决方案2】:

    你的动作类的形状是什么?我可以看到你以

    的形式发送一个动作
    {
      type: fromActions.GET_USER_SUCCESS,
      payload: res
    }
    

    但是在你的 reducer 中,你希望它有一个 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 })
            )
          )         
        );
    

    希望这会有所帮助:)

    【讨论】:

      猜你喜欢
      • 2021-12-06
      • 2018-10-16
      • 1970-01-01
      • 1970-01-01
      • 2022-06-18
      • 1970-01-01
      • 1970-01-01
      • 2018-12-05
      • 2013-07-19
      相关资源
      最近更新 更多