该问题通常出现在需要授权才能访问的页面上。在这种情况下,用户将在未登录的情况下尝试访问受保护的路由。此时,我们可以使用路由守卫来实现必须先登录才能访问的保护路由。
我们将使用CanActivate守卫接口来实现这个路由守卫。在实现路由守卫之前,我们需要在app.module.ts中导入所需的依赖项:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuardService } from './auth-guard.service';
import { LoginComponent } from './login.component';
const appRoutes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'dashboard', canActivate: [AuthGuardService] }
];
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot(appRoutes)
],
declarations: [
AppComponent,
LoginComponent
],
bootstrap: [AppComponent],
providers: [AuthGuardService]
})
export class AppModule { }
在这段代码中,我们定义了两个路径:login和dashboard。AuthGuardService将用于保护路径dashboard。当用户尝试访问此路径时,AuthGuardService将检查用户是否已经登录。如果用户没有登录,AuthGuardService会重定向到登录页面。
接下来,我们需要实现AuthGuardService:
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuardService implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(): boolean {
if (!this.authService.isAuthenticated()) {
this.router.navigate(['login']);
return false;
}
return true;
}
}
在这个示例中,AuthService是一个简单的服务,用于检查用户是否已经登录。当用户