NGRX状态属性消失

时间:2018-06-22 05:58:49

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

我正在尝试从数据库中获取用户信息。在组件中,我从服务获取已解码的ID,然后调用将ID作为参数的操作。它返回用户,“网络”选项卡中有响应。状态属性'currentUser'始终为null,直到应更改为响应,然后消失。

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 个答案:

答案 0 :(得分:0)

像这样尝试:

   

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

答案 1 :(得分:0)

您的动作班的形态如何?我可以看到您以

的形式发送操作
{
  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 })
        )
      )         
    );

希望这会有所帮助:)