Angular的AuthGuard在页面刷新时始终返回false,但我已经被认证。
创始人
2024-10-24 01:30:39
0

这可能是由于认证状态信息未能及时更新导致的。可以开启一个可观察数据流,订阅认证状态的更改,并将其保存到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(false);

constructor() { }

login(username: string, password: string) { // authenticate user this.isAuthenticated$.next(true); }

logout() { // de-authenticate user this.isAuthenticated$.next(false); }

isAuthenticated(): Observable { return this.isAuthenticated$.asObservable(); } }

// 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

相关内容

热门资讯

第6分钟了解(德州ai)外挂智... 第6分钟了解(德州ai)外挂智能ai辅助代打(透视)攻略教程(2023已更新)(哔哩哔哩);相信小伙...
第2分钟了解(tritonpo... 第2分钟了解(tritonpoker)外挂辅助插件安装代打(透视)黑科技教程(2024已更新)(哔哩...
第9分钟了解(WPK技巧)黑科... 第9分钟了解(WPK技巧)黑科技透明挂辅助软件(透视)教你攻略(2024已更新)(哔哩哔哩)是一款可...
七分钟了解(aapoker德州... 七分钟了解(aapoker德州俱乐部)软件透明挂辅助科技(透视)线上教程(2022已更新)(哔哩哔哩...
1分钟了解(Wepoke开发)... 1分钟了解(Wepoke开发)黑科技透明挂辅助黑科技(透视)扑克教程(2021已更新)(哔哩哔哩);...
第六分钟了解(wpk德州ai机... 第六分钟了解(wpk德州ai机器人)外挂辅助插件安装科技(透视)规律教程(2024已更新)(哔哩哔哩...
第1分钟了解(Wepoke技术... 第1分钟了解(Wepoke技术)外挂透明挂辅助下载(透视)实用技巧(2023已更新)(哔哩哔哩);1...
第十分钟了解(新版Wepoke... 第十分钟了解(新版Wepoke)软件透明挂辅助app(透视)曝光教程(2020已更新)(哔哩哔哩);...
第3分钟了解(wepOke)外... 第3分钟了解(wepOke)外挂辅助插件安装app(透视)第三方教程(2021已更新)(哔哩哔哩),...
八分钟了解(德扑之星设置)外挂... 八分钟了解(德扑之星设置)外挂辅助插件安装黑科技(透视)AI教程(2021已更新)(哔哩哔哩);人气...