我正在尝试使用ngrx为我的应用创建一个auth系统。
我将auth.reducer作为:
export interface State {
user: User;
authenticated: boolean;
}
const initialState: State = {
user: null,
authenticated: false
};
export type Action = authActions.All;
/// Reducer function
export function authReducer(state = initialState, action: Action) {
switch (action.type) {
case authActions.AUTHENTICATED: {
return {
...state,
authenticated: true,
user: action.payload
};
}
case authActions.LOGOUT: {
return initialState;
}
default: {
return state;
}
}
}
export const getAuthenticated = (state: State) => state.authenticated;
export const getUser = (state: State) => state.user;
和index.ts状态文件,因为我打算向此auth模块添加更多reducer:
export interface AuthState {
status: fromAuth.State;
}
export interface State extends fromStore.State {
auth: AuthState;
}
export const reducers = {
status: fromAuth.authReducer,
};
export const AuthState = createFeatureSelector<AuthState>('auth');
export const selectAuthStatusState = createSelector(
AuthState,
(state: AuthState) => state.status
);
export const getLoggedIn = createSelector(selectAuthStatusState, fromAuth.getAuthenticated);
export const getUser = createSelector(selectAuthStatusState, fromAuth.getUser);
当我尝试从组件中调用此方法以获取用户或经过身份验证的状态时,
this.authenticated$ = this.store.pipe(select(fromAuth.getLoggedIn));
this.user$ = this.store.pipe(select(fromAuth.getUser));
this.store.dispatch(new authActions.GetUser());
答案 0 :(得分:0)
将您的reducer导入AppModule或您的自定义模块,并在导入上添加以下内容
import { reducers } from './path/to/your/store/auth/reducer';
import:[
...
StoreModule.forFeature('auth', reducers),
...
],