2016-08-20 70 views
0

中的語句,我有以下 @ NGRX /存儲減速器:問題和切換減速

import {ActionReducer, Action} from '@ngrx/store'; 
import {UserAccount} from '../shared/models/useraccount.model'; 

export const SET_CURRENT_USER_ACCOUNT = 'SET_CURRENT_USER_ACCOUNT'; 
export const UPDATE_CURRENT_USER_ACCOUNT_FIRST_NAME = 'UPDATE_CURRENT_USER_ACCOUNT_FIRST_NAME'; 

export const currentUserAccountReducer: ActionReducer<UserAccount> = (state: UserAccount, action: Action) => { 

    console.log('currentUserAccountReducer:', state, action); 

    switch (action.type) { 
    case SET_CURRENT_USER_ACCOUNT: { 
     return action.payload; 
    } 
    case UPDATE_CURRENT_USER_ACCOUNT_FIRST_NAME: { 
     state.firstName = action.payload; 
     return state; 
    } 
    } 
}; 

export const SET_AUTHENTICATED = 'SET_AUTHENTICATED'; 
export const SET_UNAUTHENTICATED = 'SET_UNAUTHENTICATED'; 

export const authenticatedReducer: ActionReducer<boolean> = (state: boolean, action: Action) => { 

    console.log('authenticatedReducer:', state, action); 

    switch (action.type) { 
    case SET_AUTHENTICATED: { 
     return true; 
    } 
    case SET_UNAUTHENTICATED: { 
     return false; 
    } 
    } 
}; 

然而,由於某些原因,當我發出第一減速器調度(即currentUserAccountReducer),那麼它改變狀態的2RD減速(即authenticatedReducer)...

這裏被分派導致此問題:

this.store.dispatch({type: SET_CURRENT_USER_ACCOUNT, payload: currentUserAccount}); 

這裏是我的imports部分初始化存儲:

StoreModule.provideStore(
{ 
    currentUserAccount: currentUserAccountReducer, 
    authenticated: authenticatedReducer 
}) 

是否有人可以提供建議?

編輯:問題是,authenticated結束undefined !!

回答

3

您的減速器中的switch語句不包含default個案。您需要添加default個案,返回state,因爲還原者將被要求爲全部動作 - 商店無法知道應該爲特定動作類型調用哪個縮減器,因此每個分派動作都會傳遞給每個縮減器。

+0

非常感謝。你能解釋你的意思嗎?因爲減員會被要求採取所有行動*? – balteo

+0

你是指所有的動作類型? – balteo

+0

我已經更新了答案。 – cartant