Angular提供了基础守卫来保护路由。基础守卫是一个可以在用户导航到特定路由之前运行的函数。它可以用来验证用户是否有权限访问特定路由。
下面是一个基本的代码示例,演示如何使用基础守卫来保护路由:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable | Promise | boolean | UrlTree {
// 在这里编写验证用户权限的逻辑
const isLoggedIn = // 检查用户是否已登录,例如从本地存储中获取登录状态
if (isLoggedIn) {
return true; // 用户已登录,可以访问路由
} else {
this.router.navigate(['/login']); // 用户未登录,导航到登录页面
return false; // 阻止访问路由
}
}
}
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ProfileComponent } from './profile/profile.component';
import { AuthGuard } from './auth.guard';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'profile', component: ProfileComponent, canActivate: [AuthGuard] }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
在上面的示例中,AuthGuard
被添加到profile
路由的canActivate
属性中。这意味着在用户导航到/profile
路由之前,将会执行AuthGuard
中的canActivate
函数来验证用户权限。
如果canActivate
函数返回true
,则允许用户访问路由。如果返回false
,则用户将被导航到指定的登录页面。