页面引用后如何使用户保持当前路径?

问题描述 投票:0回答:1

所以我有基本的身份验证设置,当用户刷新页面时,我的应用程序将尝试自动登录他。现在,假设我当前位于url'/ protected / my-page-2',并且刷新页面。将会发生什么事,我将被重定向到'/ auth / login',并且当本地存储中的数据正确时((我只是在这里进行API调用)我将登录并重定向到'/ protected / my -page-1',因为该网址是我路由器中的默认路径。

这里是一些代码:

主路由器路径:

    { path: '', pathMatch: 'full', redirectTo: 'auth' },
    { path: 'auth', canActivateChild: [NoAuthGuard], loadChildren: () => import('./modules/auth/auth.module').then((m) => m.AuthModule) },
    { path: 'protected', canActivateChild: [AuthGuard], loadChildren: () => import('./modules/protected/protected.module').then((m) => m.ProtectedModule) },
    { path: '**', redirectTo: 'auth' }

受保护的路由器路径:

    { path: '', pathMatch: 'full', redirectTo: 'my-page-1' },
    { path: 'my-page-1', component: MyPage1 },
    { path: 'my-page-1', component: MyPage2 },
    { path: '**', redirectTo: 'my-page-1' }

Auth路由器路径:

    { path: '', pathMatch: 'full', redirectTo: 'login' },
    { path: 'login', component: LoginComponent },
    { path: '**', redirectTo: 'login' }

AuthGuard: (只需检查用户是否已登录)

    canActivateChild(): Observable<boolean> {
        return this.isAuthenticated$.pipe(
            map((isAuthenticated: boolean) => {
                if (isAuthenticated) {
                    return true;
                } else {
                    return false;
                }
            })
        )
    }

NoAuthGuard则相反

将用户重定向到刷新之前他访问过的最后路径的最佳方法是什么(在这种情况下为'/ protected / my-page-2'?

javascript angular authentication redirect
1个回答
0
投票

感谢我的问题下的评论,我找到了本教程[click]这正是我想要的。

© www.soinside.com 2019 - 2024. All rights reserved.