在Angular 7中,我们可以使用CanActivate
守卫来保护特定的URL。下面是一个使用CanActivate
守卫的代码示例:
auth.guard.ts
的文件,并在其中编写以下代码:import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
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): boolean {
if (this.authService.isLoggedIn()) {
return true;
}
this.router.navigate(['/login']);
return false;
}
}
auth.service.ts
的文件,并在其中编写以下代码:import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AuthService {
isLoggedIn(): boolean {
// 在这里检查用户是否已登录
// 如果已登录,返回 true,否则返回 false
return true;
}
}
app-routing.module.ts
)中,将AuthGuard
添加到需要进行身份验证的路由上。例如:import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { AuthGuard } from './auth.guard';
const routes: Routes = [
{ path: '', component: HomeComponent, canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
在这个示例中,AuthGuard
被应用于根路由和login
路由。如果用户已经登录,他们可以访问根路由,否则他们将被重定向到login
路由。
这就是使用CanActivate
守卫来保护特定URL的解决方案。请注意,这只是一个基本示例,你可以根据你的具体需求进行修改和扩展。