在Angular中,我们可以使用路由守卫(Route Guards)来实现登录页面的重定向。路由守卫提供了几个接口可以让我们在路由导航的时候进行拦截,并根据我们定义的条件来决定是否进行页面重定向。
下面是一个示例代码:
首先,在app.module.ts中导入RouterModule和Routes模块:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
// 导入需要使用路由守卫的组件
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';
// 定义路由表
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'home', component: HomeComponent, canActivate: [AuthGuard] }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
在上面代码中,定义了三个路由,分别是空路径、登录和首页。其中首页的路由添加了一个canActivate属性,值为我们接下来需要定义的路由守卫。
接下来在app目录下创建一个auth-guard.service.ts文件,并实现一个AuthGuard服务类,代码如下:
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 {
// 判断用户是否已经登录,如果未登录则重定向到登录页面
if (/* 判断是否已经登录 */) {
return true;
} else {
return this.router.navigate(['/login']);
}
}
}
``