在登录页面上实施AuthGuard

时间:2020-05-04 16:16:55

标签: angular angular-router-guards

我是路由器守卫,因此如果用户已登录,则不应允许用户继续使用/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
    }
];

1 个答案:

答案 0 :(得分:1)

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