簡體   English   中英

NGRX狀態屬性消失

[英]NGRX state property disappears

我正在嘗試從數據庫獲取用戶信息。 在組件中,我從服務獲取已解碼的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 }))); } 

像這樣嘗試:

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

您的動作課的形狀是什么? 我可以看到您以

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

希望這有所幫助 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM