How to get the previous state from Router_Cancel to ngrx?

I tried to prevent the user from moving from the current page using CanDeactivate(if the form is dirty and not saved). When we click on any link, an event is triggered Router_Navigation, and it updates the status of the router in the store, and if I cancel page navigation on the modal pop-up menu (I can disable it from deactivation), an event is raised Router_Cancelbut the current state of the router is not updated (it’s all still points to another page).

I saw this in the documentation ngrx:

ROUTER_CANCEL and ROUTER_ERROR contain the state of the repository before navigation. Use the previous state to restore the consistency of the store.

Can someone please help me on how to get the previous state from Router_CancelAction.

thank

+4
source share
1 answer

I solved this by creating an applicationRouter state to maintain current and previous routes when the ngrx router dispatches the ROUTER_NAVIGATION event, which I listen to and update the applicationRouterState application.

At each point, the applicationRouter will have only two router events (current and previous state).

and whenever Router_Cancel starts, I switch the previous router and the current state of the router.

PFB, soln:

@Effect()
    navigationListener$ = this.actions$.ofType('ROUTER_NAVIGATION')
        .pipe(
            switchMap((routerNavigationAction: RouterNavigationAction<RouterDefinition>) => {
                return of(routerNavigationAction).pipe(
                    withLatestFrom(this._routerNavigationData$),
                    map(([action, routerNavData]: [RouterNavigationAction<RouterDefinition>, RouterState]) => {
                        // TODO: Move this logic to Reducer
                        if (!(routerNavData.currentRouter && routerNavData.currentRouter.url
                            && routerNavData.previousRouter && routerNavData.previousRouter.url)) {
                            routerNavData.previousRouter = routerNavData.currentRouter =  action.payload.routerState;
                        } else {
                            routerNavData.previousRouter = routerNavData.currentRouter;
                            routerNavData.currentRouter = action.payload.routerState;
                        }
                        return new fromActions.MaintainPrevCurrRouterStateAction(routerNavData);
                    })
                );
            })
        );

And this is my state object:

export interface RouterDefinition {
    url: string;
    queryParams: Params;
    params: Params;
    segments: string[];
}
export interface RouterState {
    currentRouter: RouterDefinition;
    previousRouter: RouterDefinition;
}
0
source

Source: https://habr.com/ru/post/1693377/


All Articles