ngrx/store의 모든 상태를 재설정하는 방법은 무엇입니까?
나는 ngrx/store와 함께 Angular 2를 사용하고 있습니다.사용자 발송 시 전체 스토어 상태를 재설정합니다.USER_LOGOUT.
Redux 스토어의 상태를 재설정하는 방법에 대한 Dan Abramov의 답변을 읽었지만, 쓰는 방법을 찾지 못했습니다.rootReducerngrx/store를 사용할 때 정확하게 저장할 위치를 지정합니다.
아니면 ngrx/store에서 이를 처리할 수 있는 다른 방법이 있습니까?
bootstrap(App, [
provideStore(
compose(
storeFreeze,
storeLogger(),
combineReducers
)({
router: routerReducer,
foo: fooReducer,
bar: barReducer
})
)
]);
ngrx/store 4.x에서는 메타 리듀서를 사용하여 이 작업을 수행할 수 있습니다.제가 이해한 바로는 모든 작업이 기능 축소자에게 전달되기 전에 메타 축소자를 통과하고 있습니다.이를 통해 먼저 상태를 변경/재설정할 수 있습니다.
여기 예가 있어요.
이것은 나의 미터레듀서 기능입니다. 작업이 LOGOUT 유형인 경우 상태가 다시 초기화됩니다.
function logout(reducer) {
return function (state, action) {
return reducer(action.type === LOGOUT ? undefined : state, action);
}
}
아래에서는 형상 축소기와 함께 미터법 축소기가 구성되는 방법을 볼 수 있습니다.미터기가 1개 이상인 경우 오른쪽에서 왼쪽으로 평가됩니다.
StoreModule.forRoot({rooms: roomReducer, user: userReducer}, {metaReducers: [logout]})
마지막으로 로그인 페이지로 이동하는 @effect도 있습니다.
@Effect({dispatch: false}) logout: Observable<Action> =
this.actions$.ofType(LOGOUT)
.do(() => {
// ... some more stuff here ...
this.router.navigate(['/login page'])
});
이 답변은 ngrx 버전 2에만 해당됩니다.이 질문에는 ngrx 버전 4에서 동일한 작업을 수행할 수 있는 방법을 설명하는 또 다른 최신 답변이 있습니다.
composengrx 루트 리듀서를 빌드합니다.
전달된 인수:compose축소자를 반환하는 함수입니다. 축소자 자체에서 구성된 함수는 인수로 전달됩니다.다음과 같이 저장소 재설정을 구성할 수 있습니다.
import { compose } from "@ngrx/core/compose";
...
bootstrap(App, [
provideStore(
compose(
storeFreeze,
storeLogger(),
(reducer: Function) => {
return function(state, action) {
if (action.type === 'USER_LOGOUT') {
state = undefined;
}
return reducer(state, action);
};
},
combineReducers
)({
router: routerReducer,
foo: fooReducer,
bar: barReducer
})
)
]);
이렇게 하면 스토어의 모든 상태가 재설정됩니다. 여기에는router당신이 원하는 것이 아니라면, 당신은 예제를 수정할 수 있습니다.
의 소개로NgModule부트스트래핑이 변경되었지만, 여전히 합성된 감속기를 에 전달합니다.provideStore:
import { compose } from "@ngrx/core/compose";
import { StoreModule } from "@ngrx/store";
@NgModule({
...
imports: [
...
StoreModule.provideStore(compose(...))
],
...
@ngrx/store": "^4.0.3"의 경우, 작은 변화가 있기 때문에 약간 다르기 때문에 내 'clear state'는 다음과 같습니다.
import { ActionReducerMap } from '@ngrx/store';
import { ActionReducer, MetaReducer } from '@ngrx/store';
export const rootReducer: ActionReducerMap<StoreStates> = {
points: pointsReducer,
...
};
export function clearState(reducer: ActionReducer<StoreStates>): ActionReducer<StoreStates> {
return function(state: StoreStates, action: Action): StoreStates {
if (action.type === 'CLEAR_STATE') {
state = undefined;
}
return reducer(state, action);
};
}
export const metaReducers: MetaReducer<StoreStates>[] = [clearState];
그리고.
import { StoreModule } from '@ngrx/store';
import { metaReducers, rootReducer } from '../root.reducer';
export const imports: any = [
StoreModule.forRoot(rootReducer, { metaReducers }),
...
]
이것은 사실 답은 아니지만 댓글을 통해 정확한 형식을 지정할 수 없습니다.다음과 같이 유형을 설정하는 경우 카탕트의 설명에 추가합니다.
export const ActionTypes = {
LOGOUT: type('[Environment] Logout of portal'),
....
}
이것은 당신이 사용해야 할 긴 설명입니다.또한 루트 리듀서의 이름을 지정하는 경우rootReducer의 대신에reducer그러면 당신도 그것을 바꿀 것입니다.다음은 편집된 예제입니다.
(이 기능은 루트 리듀서 내에 남겨두었습니다)
const developmentReducer: ActionReducer<State> = compose(...DEV_REDUCERS,
(rootReducer: Function) => {
return function(state, action) {
if (action.type === '[Environment] Logout of portal') {
state = undefined;
}
return rootReducer(state, action);
};
}, combineReducers)(reducers);
[업데이트 2022]
이 블로그 게시물은 Angular 14의 매력처럼 작동하며 구현하기 매우 쉽습니다.원하는 작업을 사용하여 저장소를 재설정할 수 있습니다.https://www.purcellyoon.com/insights/articles/angular-ngrx-8-reset-state-using-meta-reducer
actions.ts에서 로그아웃 작업 정의
import { createAction, props } from '@ngrx/store';
export const logoutSuccess = createAction('[Authentication] Logout Success');
reducers.ts에서 메타리듀서를 정의합니다.
import { ActionReducer, ActionReducerMap, INIT, MetaReducer } from '@ngrx/store';
import * as AuthActions from './actions';
export const reducers: ActionReducerMap<State> = {
[featureKey1]: reducer1,
[featureKey2]: reducer2,
//...
}
export const logout = (reducer: ActionReducer<any>): ActionReducer<any> => {
return (state, action) => {
if (action !== null && action.type === AuthActions.logoutSuccess.type) {
return reducer(undefined, { type: INIT });
}
return reducer(state, action);
};
};
export const metaReducers: MetaReducer[] = [logout];
app.store.dll.ts
import { metaReducers, reducers } from '../store/reducers';
@NgModule({
imports: [
StoreModule.forRoot(reducers, {
metaReducers,
runtimeChecks: {
strictStateImmutability: true,
strictActionImmutability: true
}
}),
이제 구성 요소에 작업을 배치합니다.
this.store.dispatch(logout());
즉, 로그아웃 성공 작업을 발송하여 사용자가 로그아웃하고 저장소가 재설정되도록 합니다.
logout$ = createEffect(() => this.actions$.pipe(
ofType(Actions.logout),
mergeMap((action) =>
this.apiService.logout().pipe(
map((user: User) => Actions.logoutSuccess()),
catchError((error) => of(Actions.logoutFailure({ error })))
)
)
));
언급URL : https://stackoverflow.com/questions/39323285/how-to-reset-all-states-of-ngrx-store
'code' 카테고리의 다른 글
| 'UploadMappingFileTask' 유형 속성 'googleServicesResourceRoot'에 구성된 값이 없습니다. (0) | 2023.06.07 |
|---|---|
| C에서 변수 이름을 얻는 프로그래밍 방식? (0) | 2023.06.07 |
| GitHub의 프로젝트 대 저장소 (0) | 2023.06.07 |
| MySQL View에서 결과가 없을 때 값을 반환하려면 어떻게 해야 합니까? (0) | 2023.06.07 |
| 쿼리 크기 찾기 (0) | 2023.06.07 |