您可以在初始化器中使用Auth service来检查用户是否已登录,然后在app.module.ts中添加AuthGuard,以确保用户已登录才能访问应用程序。例如:
在app.module.ts中添加AuthGuard:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from './auth.guard';
const routes: Routes = [
// 这是需要登录才能访问的页面
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
// 其他页面
{ path: '**', component: NotFoundComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
创建AuthGuard来检查用户是否已登录:
import { Injectable } from '@angular/core';
import { CanActivate, 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(): boolean {
if (!this.authService.isLoggedIn()) {
this.router.navigate(['/login']);
return false;
}
return true;
}
}
在AuthService中添加isLoggedIn()方法:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private isLoggedIn = false;
constructor() { }
// 用户已登录返回true,否则返回false
public isLoggedIn(): boolean {
return this.isLoggedIn;
}
}
现在你可以在你的初始化器中使用AuthService的isLoggedIn()方法来检查用户是否已登录。如果用户已经登录,你可以通过AuthService的setLoggedIn()方法来设置isLoggedIn为true。