Angular: 激活后屏蔽路由

Angular: block a route after activating it

我正在开发一个 Angular 应用程序,我的仪表板组件中有一个登录页面。我在 table 组件中显示了一组数据。我已经成功屏蔽了用户登录后才能访问的table路由。我想做的是在用户登录dashboard组件后,我想屏蔽dashboard组件,这样用户在注销之前无法再次访问登录部分,这是我的第三个组件。我试过在下面这样做,但没有用。这是我的代码:

admin-layout.routing.ts

export const AdminLayoutRoutes: Routes = [
{ path: 'dashboard', canActivate: [RoleGuard],     component: DashboardComponent },
{ path: 'user',           component: UserComponent },
{ path: 'table',  canActivate: [AuthGuard],        component: TableComponent },
{ path: 'icons',          component: IconsComponent }
];

auth-guard.service.ts //for the protection of my table component

constructor(private authService: AuthService, private router: Router){}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean
  {
   if(this.authService.isAuthenticated())
    {
      return true;
    }
    this.router.navigateByUrl('/dashboard');
    return false;
  }

role-guard.service.ts //for the protection of my dashboard component(login page)

constructor(private router: Router, private authService: AuthService){}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : boolean
{
  if(this.authService.isNotAuthenticated)
  {
    console.log("role guard True cond."); //this gets printed on console always, even after I login

    return true;
  }
  console.log("role guard false cond.")
  this.router.navigateByUrl('/table');
  return false;
}

auth.service.ts //for defining the logic of the above two guards

 export class AuthService
 {
 loggedIn:boolean = false;

 check_Authentication(logIn : boolean)
 {
  if(logIn == true)
  {
    this.loggedIn = true;
  }
  else
  {
    this.loggedIn = false;
  }
 }

isAuthenticated()
{
 if(this.loggedIn == true)
 {
   return true;
 }
 else
 {
   return false;
 }
}

isNotAuthenticated()
{
 if(this.loggedIn != true)
 {
   return true;
 }
 else
 {
   return false;
 }
}

}

dashboard.component.ts //I am sending the variable as true if the user has logged in, here

private onAuthorization(form: NgForm)
{
  this.http.post('http://localhost:3000/auth', form.value, {responseType: "text"})
  .subscribe(responseData =>{
    console.log(responseData);
    if(responseData == "Successfully Authorized")
    {
      this.auth_check = true;
      this.authService.check_Authentication(this.auth_check);
      if(this.authService.isAuthenticated)
      {
        this.router.navigateByUrl('/table');
      }
    }
    else
    {
      this.auth_failed = true;
    }

  }
  ,error => {
    this.connectionToServer = false;
  });
  this.connectionToServer = true;
}

谁能告诉我我做错了什么?编辑:在我将用户导航到 table 页面后,登录页面没有被阻止,这是应该的。

我刚刚检查了你的代码,登录后你需要在本地存储中设置一个可以从任何服务访问的值。

例如:

if(responseData === "Successfully Authorized")
{
    localStorage.setItem('loggedIn', true);
}

在你的 auth guard 中,你只需要检查 localstorage 是否有价值,就像这样

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean
{
   let isLoggedIn = localStorage.getItem('loggedIn');
   if (isLoggedIn) {
      return true;
   }
   this.router.navigateByUrl('/dashboard');
   return false;
}

需要在您的 Role Guard 中执行此操作

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : boolean
{
  const isLoggedIn = localStorage.getItem('loggedIn');
  if(!isLoggedIn)
  {
    console.log("role guard True cond."); //this gets printed on console always, even after I login
    return true;
  }
  console.log("role guard false cond.");
  this.router.navigateByUrl('/table');
  return false;
}

希望对您有所帮助。谢谢

我犯了一个简单的错误,但对我来说效果很好。

除了

,一切都保持不变

role-guard.service.ts //for the protection of my dashboard component(login page)

constructor(private router: Router, private authService: AuthService){}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : boolean
{
  if(this.authService.isNotAuthenticated()) //I was missing parenthesis in my function 
                                            //call here
  {
  console.log("role guard True cond."); //this gets printed on console always, even 
                                        //after I login

  return true;
  }
 console.log("role guard false cond.")
 this.router.navigateByUrl('/table');
 return false;
 }

我看到了你的代码,你可以使用三个助手 methods 并在成功登录时将用户状态存储在 localStorage 中,在注销时删除状态(令牌)。第三个是getState(): boolean判断用户状态

  1. 设置state成功登录
private saveState(token: string): void {
  localStorage.setItem('state', 'true');
  this.token = token;
}

2) 注销时删除 state

logout(){
      localStorage.removeItem('token');
      this.router.navigate(['/login'])
}

3) 通过 state 验证用户,并根据 truefalse 响应

完成您的工作
 private getState(): boolean {
      let token = localStorage.getItem('state');
      if(token){
        return true;
      }
      else {
        return false;
      }