【发布时间】:2022-08-18 18:38:43
【问题描述】:
为了跨组件获取持久的用户信息,我试图在我的解决方案中实现 NgRx 存储,但一直坚持使用选择器从存储中获取数据。
通过控制台返回的错误是用户(AuthState 的一部分)未定义,但登录时我将其传递给商店,并且在多次扩展源时可以看到它。
我一直在关注文档https://www.npmjs.com/package/ngrx-store-localstorage,但现在有点卡住了,欢迎任何有关如何有效进行或调试的建议。
零件
this.store.dispatch(addUser({ data: userDetails }));
行动
export const addUser = createAction(
\'[Auth] Add user\',
props<{ data: LoggedUserDetails }>()
);
export const loadUser = createAction(
\'[Auth] Load user\'
);
减速器
export const initialAuthState: AuthState = {
user: {
email: \'\',
accessToken: \'\',
idToken: \'\',
name: \'\',
id: \'\'
},
authenticated: false
};
// handles the retrieval of the user details
export const authReducer = createReducer(
initialAuthState,
on(addUser, (state, { data }) => ({
...state,
user: data,
authenticated: true
})),
on(loadUser, (state) => ({
...state,
user: state.user,
authenticated: state.authenticated
}))
);
选择器
export const selectAuthState = (state: AppState) => state.authState;
export const selectUserDetails = createSelector(
selectAuthState,
(authState: AuthState) => authState.user);
模块
export function localStorageSyncReducer(
reducer: ActionReducer<any>
): ActionReducer<any> {
return localStorageSync({ keys: [\'auth\'], rehydrate: true })(reducer);
}
const metaReducers: Array<MetaReducer<any, any>> = [localStorageSyncReducer];
// within the imports rather than copying the entire module
StoreModule.forRoot(
authReducer, { metaReducers }
)
共享组件
this.store.pipe(select(selectUserDetails)).subscribe((res: LoggedUserDetails) => {
// accessing from a shared component this gives the user is undefined error
this.userDetails = res;
});
-
所以最初你看到
undefined,但是在你登录后,选择器返回数据还是继续传递undefined? -
loadUser 做什么..?
-
不断交付 undefined 和 loadUser 旨在用于从商店中带回用户详细信息。
标签: angular ngrx ngrx-store