返回的Ngrx存储值是true,但尝试访问它却给出了未定义的值

问题描述

状态值根据reducer返回true或false,但无法访问未定义的状态。

这是我的组件代码

getState : Observable<any>;


   isAuthenticated : false;
      user = null;
      errorMessage = null;

  constructor( private store : Store<AppState>) {
    this.getState = this.store.select(selectAuthState);
   }

    ngOnInit(): void {
        this.getState.subscribe((state)=>{
          this.isAuthenticated = state.isAuthenticated;
          this.user = state.user;
          this.errorMessage = state.errorMessage;           
        });
      }

state.ts代码

 export interface AppState{
        authState : auth.State;
    }
    
    export const reducers = {
        auth : auth.reducer
    }
    
    export const selectAuthState = createFeatureSelector<AppState>('auth');

减速器代码

export interface State{
    isAUthenticated : boolean;

    user : User | null;

    errorMessage : string | null;

}

export const initialState : State = {
    isAUthenticated : false,user : null,errorMessage : null
}


export function reducer (state = initialState,action : All) : State{
    switch(action.type){
        case AuthActionTypes.LOGIN_SUCCESS : {
            return{
                ...state,isAUthenticated:true,user:{
                    token : action.payload.token,email : action.payload.email
                },errorMessage : null
            };
        }
        case AuthActionTypes.LOGIN_FAILURE : {
            return{
                ...state,errorMessage : 'Incorrect email and/or password'
               
            };            
        } 
        case AuthActionTypes.SIGNUP_SUCCESS :{
            return{
                isAUthenticated : true,user:{
                    token:action.payload.token,email:action.payload.email
                },errorMessage: null
            };
        }
        case AuthActionTypes.SIGNUP_FAILURE : {
            return{
               ...state,errorMessage : 'That email is already in use.'
             };
        }
        case AuthActionTypes.logoUT : {
            return initialState;
        }

        case AuthActionTypes.RESET :{
            return initialState;
        }
        
        default : {
            return state;
        }
    }
}

您可以看到返回的状态值为true,但是state.isAuthenticated未定义。我什至在状态值相应更改的redux devtools中查看了状态值。

debug

解决方法

您输入的错字是“ isAUthenticed”和“ isAuthenticated”

      case AuthActionTypes.SIGNUP_SUCCESS :{
            return{
                isAUthenticated : true,user:{
                    token:action.payload.token,email:action.payload.email
                },errorMessage: null
            };
        }

您的调试消息也显示此错字