首页 > 解决方案 > NGRX 状态属性消失

问题描述

我正在尝试从数据库中获取用户信息。在组件中,我从服务中获取解码的 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
    })));
  }

标签: javascriptangularngrxngrx-storengrx-effects

解决方案


试试这样:

   

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


推荐阅读