当然有一个简单的方法。只需制作一个效果代理来处理路由操作并像使用任何其他 NGRX 效果一样使用路由器:
@Injectable()
export class RouterEffects {
@Effect({ dispatch: false })
navigate$ = this.actions$.ofType(RouterActions.GO)
.map((action: RouterActions.Go) => action.payload)
.do((routerPayload: RouterPayload) => {
this.router.navigate(routerPayload.path, routerPayload.query);
});
@Effect({ dispatch: false })
navigateBack$ = this.actions$.ofType(RouterActions.BACK)
.do(() => this.location.back());
@Effect({ dispatch: false })
navigateForward$ = this.actions$.ofType(RouterActions.FORWARD)
.do(() => this.location.forward());
constructor(
private actions$: Actions,
private router: Router,
private location: Location
) {}
}
使用 router.actions.ts:
export const GO = '[Router] Go';
export const BACK = '[Router] Back';
export const FORWARD = '[Router] Forward';
export interface RouterPayload {
path: string[];
query?: NavigationExtras;
}
export class Go implements Action {
readonly type = GO;
constructor(public payload: RouterPayload) {}
}
export class Back implements Action {
readonly type = BACK;
}
export class Forward implements Action {
readonly type = FORWARD;
}
export type Actions
= Go
| Back
| Forward;
并且在您的组件中,您在导航上调度路由器操作,而不是直接在模板中调用 routerLink:
navigate(routerPayload: RouterPayload) {
this.store.dispatch(new RouterActions.Go(routerPayload));
}
这样,您也可以轻松地在路线中来回走动。