简体   繁体   English

NGRX状态属性消失

[英]NGRX state property disappears

I'm trying to get user info from database. 我正在尝试从数据库获取用户信息。 In component I'm getting decoded id from service, then call the action which takes the id as parameter. 在组件中,我从服务获取已解码的ID,然后调用将ID作为参数的操作。 It returns the user, there is response in network tab. 它返回用户,“网络”选项卡中有响应。 The state property 'currentUser' is null all the time until it should change to response, then it disappears. 状态属性“ 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 }))); } 

Try it like this: 像这样尝试:

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

What is the shape of your action class? 您的动作课的形状是什么? I can see you dispatch an action in the shape of 我可以看到您以

{
  type: fromActions.GET_USER_SUCCESS,
  payload: res
}

but in your reducer you expect it to have a user property on it 但是在减速器中,您希望它具有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
  };
}

Also, try to shape your effect more like this: 此外,尝试更像这样来塑造效果:

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

Hope this helps a little :) 希望这有所帮助 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM