MST

星途 面试题库

面试题:Angular路由守卫之CanActivate的应用

在Angular应用中,如何使用CanActivate路由守卫来保护特定路由,只有登录用户才能访问?请描述实现步骤,并给出一个简单的代码示例。
17.0万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试
  1. 实现步骤
    • 创建一个实现CanActivate接口的服务。
    • 在该服务的canActivate方法中,编写逻辑来判断用户是否已登录。通常可以通过检查本地存储、JWT令牌或者应用内的登录状态变量等方式。
    • 将这个服务配置到需要保护的路由的canActivate属性中。
  2. 代码示例
    • 创建路由守卫服务
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AuthService } from './auth.service'; // 假设存在一个用于管理登录状态的服务

@Injectable({
  providedIn: 'root'
})
export class AuthGuardService implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    if (this.authService.isLoggedIn()) {
      return true;
    } else {
      this.router.navigate(['/login']); // 重定向到登录页面
      return false;
    }
  }
}
  • 在路由模块中使用守卫
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { AuthGuardService } from './auth - guard.service';

const routes: Routes = [
  { path: 'home', component: HomeComponent, canActivate: [AuthGuardService] },
  { path: 'login', component: LoginComponent },
  { path: '**', redirectTo: 'login' }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}
  • 假设的AuthService示例
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private isLoggedInStatus = false;

  login() {
    this.isLoggedInStatus = true;
  }

  logout() {
    this.isLoggedInStatus = false;
  }

  isLoggedIn() {
    return this.isLoggedInStatus;
  }
}