要在Angular中使用AuthGuard对子路由进行拦截,需要按照以下步骤操作:
ng generate service auth-guard
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 | Promise | boolean | UrlTree {
// 在这里添加你的身份验证逻辑
if (this.authService.isLoggedIn()) {
return true;
} else {
// 没有权限访问,重定向到登录页
this.router.navigate(['/login']);
return false;
}
}
}
ng generate service auth
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private loggedIn = false;
constructor() { }
// 模拟用户登录
login(username: string, password: string) {
if (username === 'admin' && password === 'admin123') {
this.loggedIn = true;
}
}
// 模拟用户注销
logout() {
this.loggedIn = false;
}
// 返回用户登录状态
isLoggedIn() {
return this.loggedIn;
}
}
dashboard
的父路由,其中包含一个名为profile
的子路由。打开你的路由模块(通常是app-routing.module.ts),并添加以下代码:import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from './auth-guard.service';
import { DashboardComponent } from './dashboard.component';
import { ProfileComponent } from './profile.component';
const routes: Routes = [
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [AuthGuard], // 使用AuthGuard来保护父路由
children: [
{
path: 'profile',
component: ProfileComponent,
canActivate: [AuthGuard] // 使用AuthGuard来保护子路由
}
]
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
/dashboard/profile
时,AuthGuard将会检查用户的登录状态。如果用户已登录,他们将被允许访问该路由,否则将被重定向到登录页。这样,你就可以使用AuthGuard对Angular中的子路由进行拦截了。请记得根据你的具体需求修改AuthGuard中的身份验证逻辑和AuthService中的登录逻辑。