当前位置: 代码网 > it编程>前端脚本>AngularJs > Angular中AuthGuard路由守卫的创建使用

Angular中AuthGuard路由守卫的创建使用

2024年05月18日 AngularJs 我要评论
angular中的authguardangular 中的 authguard 是一个路由守卫,它用于保护某些路由,只有当用户经过身份验证并具有访问权限时,才允许他们访问。authguard 通常与路由

angular中的authguard

angular 中的 authguard 是一个路由守卫,它用于保护某些路由,只有当用户经过身份验证并具有访问权限时,才允许他们访问。authguard 通常与路由配置一起使用,以确保用户无法直接访问需要身份验证的页面。

创建

authguard 是一个 angular 服务,可以使用以下命令来创建它:

ng g guard auth

上面的命令将生成一个名为“auth”的 authguard,并将其添加到 src/app/auth.guard.ts 文件中。

auth.guard.ts 文件中的代码如下所示:

import { injectable } from '@angular/core';
import { canactivate, activatedroutesnapshot, routerstatesnapshot, urltree, router } from '@angular/router';
import { observable } from 'rxjs';
import { authservice } from './auth.service';

@injectable({
  providedin: 'root'
})
export class authguard implements canactivate {
  constructor(private authservice: authservice, private router: router) {}

  canactivate(
    next: activatedroutesnapshot,
    state: routerstatesnapshot): observable<boolean | urltree> | promise<boolean | urltree> | boolean | urltree {
    if (this.authservice.isloggedin()) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}

在上面的代码中,authguard 是通过实现 canactivate 接口来定义的。canactivate 接口包含一个名为 canactivate() 的方法,该方法决定了当用户尝试访问受保护的路由时应该执行哪些操作。

在 authguard 中,我们注入了一个名为 authservice 的服务和 router 对象。authservice 用于检查用户是否已经登录,而 router 用于导航到登录页面或者用户试图访问的页面。在 canactivate() 方法中,我们首先调用 this.authservice.isloggedin() 方法来检查用户是否已经登录。如果用户已经登录,我们返回 true,表示用户可以访问该路由。否则,我们调用 this.router.navigate(['/login']) 方法,将用户重定向到登录页面,然后返回 false,表示用户无法访问该路由。

authguard保护一个路由

要使用 authguard 来保护一个路由,我们需要在路由配置中将 authguard 添加到 canactivate 属性中。例如:

import { ngmodule } from '@angular/core';
import { routes, routermodule } from '@angular/router';
import { homecomponent } from './home/home.component';
import { dashboardcomponent } from './dashboard/dashboard.component';
import { logincomponent } from './login/login.component';
import { authguard } from './auth.guard';
const routes: routes = [
  { path: '', component: homecomponent },
  { path: 'dashboard', component: dashboardcomponent, canactivate: [authguard] },
  { path: 'login', component: logincomponent },
];
@ngmodule({
  imports: [routermodule.forroot(routes)],
  exports: [routermodule]
})
export class approutingmodule { }

在上面的代码中,我们将 authguard 添加到了 /dashboard 路由的 canactivate 属性中,这意味着只有当用户已经登录时才能访问 /dashboard 路由。

以上就是angular中authguard路由守卫的创建使用的详细内容,更多关于angular authguard创建使用的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com