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创建使用的资料请关注代码网其它相关文章!
发表评论