假设用户前往http://sample.com/dashboard然后登录后卫检查并且他没有登录并将他重定向到登录页面。我想得到他的最后一条路线(在这个例子中是http://sample.com/dashboard),当他登录时将他重定向到路线。我只是用Ngrx效果做到了,但......
@Effect()
getUserLoginData$: Observable<Action> = this.actions$.pipe(
ofType(userActions.GET_USER_DATA),
switchMap(() => {
return this.sessionService.getLoggedInUserInfo().pipe(
map((success) => new userActions.GetUserDataSuccessAction(success)),
catchError((error) => of(new uerActions.GetUserDataFailAction(error)))
);
})
);
@Effect({dispatch: false})
public userLoginDataSuccess$: Observable<Action> = this.actions$.pipe(
ofType(userActions.GET_USER_DATA_SUCCESS),
map((action: userActions.GetUserDataSuccessAction) => action),
tap((data) => {
if (data.url.includes('login'))
this.router.navigate([RouteMap.DASHBOARD])
else
this.router.navigate([data.url])
})
);
您可以创建一个跟踪路线历史记录的服务。
previousUrl: string;
constructor(router: Router) {
router.events
.filter(event => event instanceof NavigationEnd)
.subscribe(e => {
console.log('prev:', this.previousUrl);
this.previousUrl = e.url;
});
}
您可以将其与您的州管理集成。
其实我找到了答案:
1-将routerReducer添加到您的状态界面:
export interface State {
...
routerReducer: fromRouter.RouterReducerState<RouterStateUrl>;
}
2- Reducer对象中的InitReducer:
export interface State {
...
routerReducer: fromRouter.RouterReducerState<RouterStateUrl>;
}
3-创建RouterSatetUrl接口:
export interface RouterStateUrl {
url: string;
params: Params;
queryParams: Params;
}
4-创建CustomSerializer:
@Injectable()
export class CustomSerializer implements fromRouter.RouterStateSerializer<RouterStateUrl> {
serialize(routerState: RouterStateSnapshot): RouterStateUrl {
const {url} = routerState;
const {queryParams} = routerState.root;
let state: ActivatedRouteSnapshot = routerState.root;
while (state.firstChild) {
state = state.firstChild;
}
const {params} = state;
return {url, params, queryParams};
}
}
5-创建FeatureSelector以随时获取当前路径:
export const getRouterState = createFeatureSelector<fromRouter.RouterReducerState<RouterStateUrl>>('routerReducer');
6-最后一步是使用getRouterState来获取路径信息。例如,我在我的一个效果中使用它:
@Effect({dispatch: false})
public userLoginDataSuccess$: Observable<Action> = this.actions$.pipe(
ofType(userActions.GET_USER_DATA_SUCCESS),
map((action: userActions.GetUserDataSuccessAction) => action),
tap(() => {
let getRouterState$ = this.store.select(fromRoot.getRouterState).subscribe((data) => {
if (!data.state || data.state.url.includes('login') || data.state.url == '/' || data.state.url == '') {
this.router.navigate([RouteMap.DASHBOARD])
} else {
this.router.navigate([data.state.url])
}
});
getRouterState$.unsubscribe();
})
);
试试history.back()
问候!