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

相关内容

热门资讯

相较于以往!手机透视辅助器ap... 相较于以往!手机透视辅助器app!确实存在有辅助神器(有挂助手)-哔哩哔哩1、上手简单,内置详细流程...
备受关注的!同城乐吧乐享版51... 备受关注的!同城乐吧乐享版510k辅助!竟然是真的辅助下载(有挂分析)-哔哩哔哩1、同城乐吧乐享版5...
目前!乐乐休闲游戏辅助!一贯真... 目前!乐乐休闲游戏辅助!一贯真的是有辅助工具(真实有挂)-哔哩哔哩1、首先打开乐乐休闲游戏辅助辅助器...
来临!微信多乐小程序游戏破解器... 来临!微信多乐小程序游戏破解器!一贯是有辅助平台(确实有挂)-哔哩哔哩1、超多福利:超高返利,海量正...
近年来!闲逸有没有辅助软件功能... 近年来!闲逸有没有辅助软件功能!好像存在有辅助神器(有挂教程)-哔哩哔哩该软件可以轻松地帮助玩家将闲...
截至目前!博雅红河西元!一直真... 截至目前!博雅红河西元!一直真的有辅助神器(确实有挂)-哔哩哔哩1、在博雅红河西元插件功能辅助器技巧...
长期以来!约战丹东游戏辅助器!... 长期以来!约战丹东游戏辅助器!一贯真的有辅助平台(有挂详情)-哔哩哔哩1、许多玩家不知道约战丹东游戏...
在玩家背景下!人海大厅脚本!竟... 在玩家背景下!人海大厅脚本!竟然有挂辅助安装(有挂分享)-哔哩哔哩1、首先打开人海大厅脚本辅助器下载...
据了解!宁德钓螃蟹有没有挂!一... 据了解!宁德钓螃蟹有没有挂!一贯是有辅助下载(有挂讲解)-哔哩哔哩所有人都在同一条线上,像星星一样排...
有消息称!哈糖大菠萝能开挂吗!... 有消息称!哈糖大菠萝能开挂吗!一贯是有辅助修改器(有挂详细)-哔哩哔哩;所有人都在同一条线上,像星星...