在登录页面上实现 AuthGuard

Implementing AuthGuard on login page

我是路由器守卫所以如果用户已经登录,那么它不应该允许用户继续/login。但是即使我登录了,我也可以去 /login

这是 authGuard

export class AuthGuard implements CanActivate {
    constructor(private apiService: ApiService,
                private router: Router) {
    }

    canActivate(
        route: ActivatedRouteSnapshot,
        router: RouterStateSnapshot):
        | boolean
        | UrlTree
        | Promise<boolean | UrlTree>
        | Observable<boolean | UrlTree> {
        return this.apiService.session.pipe(
            take(1),
            map(session => {
                const isAuth = !!session;
            if (isAuth) {
                    return true;
                }
                return this.router.createUrlTree(['/login']);

            })
        );
    }
}

路由模块


const routes: Routes = [
    {
        path: 'login',
        component: LoginComponent,
    },
    {
        path: 'dashboard',
        canActivate: [AuthGuard],
        component: DashboardComponent
    }
];

login 路线建立守卫(与您的 AuthGuard 基本相似,但逻辑相反):

@Inject({providedIn: 'root'})
export class AuthLoginGuard implements CanActivate {
  constructor(private apiService: ApiService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot,
      router: RouterStateSnapshot): Observable<boolean | UrlTree> {
    return this.apiService.session.pipe(
      take(1),
      map(session => session ? this.router.createUrlTree(['/dashboard']) : true)
    );
  }
}

并将其添加到您的登录路径:

const routes: Routes = [
  {
    path: 'login',
    component: LoginComponent,
    canActivate: [AuthLoginGuard]
  },
  {
    path: 'dashboard',
    canActivate: [AuthGuard],
    component: DashboardComponent
  }
];