Angular router guard and ROUTER_NAVIGATION effect order

房东的猫 提交于 2019-12-04 11:44:29

There is one way to achieve it. You can subscribe to the Angular Router's ResolveEnd event https://angular.io/api/router/ResolveEnd in your effect and then dispatch your own action for RESOLVE_END where you can do stuff with your resolver / guard data.

Actually there is an PR in ngrx/platform that I created where ngrx/router will dispatch NAVIGATE_RESOLVE_END action out of the box. I am waiting for ngrx team to accept my PR. https://github.com/ngrx/platform/pull/524/

You can subscribe to router events and filter it for the Resolve End and dispatch your own action call it Router_Resove_End action etc.

this.router.events.filter(e => e instanceof ResolveEnd).subscribe(s => {
 // dispatch your own action here.
});

There is very nice wrap up on Medium:

@Injectable()
export class RouterEffects {
    constructor(
        private actions$: Actions,private router: Router,private location: Location,private store: Store<any>
    ) {this.listenToRouter();}

    @Effect({ dispatch: false })
    navigate$ = this.actions$.pipe(ofType('[Router] Go')...);
    @Effect({ dispatch: false })
    navigateBack$ = this.actions$.pipe(ofType('[Router] Back'), tap(() => this.location.back()));

    @Effect({ dispatch: false })
    navigateForward$ = this.actions$.pipe(ofType('[Router] Forward'),...);

    private listenToRouter() {
        this.router.events.pipe(
            filter(event => event instanceof ActivationEnd)
        ).subscribe((event: ActivationEnd) =>
            this.store.dispatch(new RouteChange({
                params: { ...event.snapshot.params },
                path: event.snapshot.routeConfig.path
            }))
        );
    }
}

and then instead of:

@Effect() routeChange$ = this.actions$.ofType(ROUTER_NAVIGATION)

use:

@Effect() routeChange$ = this.actions$.ofType(ofType('[Router] Route Change'))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!