这可能是由于认证状态信息未能及时更新导致的。可以开启一个可观察数据流,订阅认证状态的更改,并将其保存到localStorage或sessionStorage中。在AuthGuard中,从关联的存储中读取状态信息,而不是直接从认证服务中获取。这样,在页面刷新后,状态信息将保持不变,AuthGuard将能够正确地返回true。
以下是一个可能的实现示例:
// authService.ts
import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private isAuthenticated$ = new BehaviorSubject
constructor() { }
login(username: string, password: string) { // authenticate user this.isAuthenticated$.next(true); }
logout() { // de-authenticate user this.isAuthenticated$.next(false); }
isAuthenticated(): Observable
// authGuard.ts
import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router'; import { Observable } from 'rxjs'; 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): Observable
return this.authService.isAuthenticated().pipe(
map((isAuthenticated) => {
if (isAuthenticated) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
})
);
} }
// app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router';
import { AppComponent } from './app.component'; import { LoginComponent } from './login/login.component'; import { HomeComponent } from './home/home.component'; import { AuthGuard } from './auth.guard'; import { AuthService } from './auth.service';
const app