首页 > 解决方案 > 当用户重定向到登录时如何保留最后一条路线-by Ngrx Effect angular

问题描述

假设用户访问http://sample.com/dashboard然后登录保护检查并且他没有登录并将他重定向到登录页面。我想获得他的最后一条路线(在此示例中为http://sample.com/dashboard),并在他登录时将他重定向到该路线。我只是用 Ngrx Effect 做到的,但是......

    @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])
    })
  );

标签: angularngrxeffect

解决方案


例如,您可以创建一个服务来跟踪您的路线历史。

previousUrl: string;
constructor(router: Router) {
  router.events
  .filter(event => event instanceof NavigationEnd)
  .subscribe(e => {
    console.log('prev:', this.previousUrl);
    this.previousUrl = e.url;
  });
}

您可以将其与您的状态管理集成。


推荐阅读