Angular中的AuthGuard无法正常工作。
创始人
2024-10-31 02:30:26
0
  1. 首先,确保你已经正确地设置了 AuthGuard,并且在路由中使用了它,如下所示:

import { AuthGuard } from './auth.guard';

const routes: Routes = [ { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }, { path: 'login', component: LoginComponent } ];

  1. 检查 AuthGuard 中的代码是否正确。确保它返回一个布尔值,以指示用户是否已授权。以下是一个示例:

import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router'; import { Observable } from 'rxjs'; import { AuthService } from './auth.service';

@Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate {

constructor(private authService: AuthService) {}

canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable | Promise | boolean | UrlTree { return this.authService.isLoggedIn(); } }

  1. 检查 AuthService 中用于检查用户是否已登录的代码。以下是一个示例:

import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs';

@Injectable({ providedIn: 'root' }) export class AuthService {

private loggedIn = new BehaviorSubject(false);

constructor() { }

isLoggedIn() { return this.loggedIn.asObservable(); }

login() { // perform login tasks this.loggedIn.next(true); }

logout() { // perform logout tasks this.loggedIn.next(false); } }

  1. 最后,确保你在用户登录时调用了 AuthService 的 login() 方法,并在用户注销时调用了 logout() 方法。这将确保 AuthGuard 能够正确地检查用户的授权状态。

相关内容

热门资讯

wepoke有辅助挂!德州ai... WePoker透视辅助工具核心要点解析‌,wepoke有辅助挂!德州ai辅助app,(AAPOKEr...
透视线上(aa扑克辅助)gov... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在这款游戏中打牌都...
aapoker有猫腻!fish... aapoker有猫腻!fishpoker大菠萝外挂,(WpK)一向有挂(详细透视详细教程)1、每一步...
透视科技(德州免费辅助神器ap... 透视科技(德州免费辅助神器app)wepoke开发者(详细辅助黑科技教程)都是真的是有挂1、让任何用...
aa扑克辅助!德州ai人工智能... 1、aa扑克辅助!德州ai人工智能软件下载,(wepoke)本来有挂(详细辅助软件教程);详细教程。...
透视讲解(wpk提高胜率)we... 透视讲解(wpk提高胜率)wepower德州辅助器(详细辅助科技教程)往昔是真的有挂(1)透视讲解(...
透视ai(德州ai人工智能)w... 1、透视ai(德州ai人工智能)wepoke有正规吗(详细辅助可靠教程)固有存在有挂2、进入游戏-大...
wpk透视辅助工具!红龙扑克是... WePoker透视辅助工具核心要点解析‌,wpk透视辅助工具!红龙扑克是不是有问题,(aApoker...
透视好牌(智星德州菠萝有挂吗)... 透视好牌(智星德州菠萝有挂吗)wpk怎么玩胜率高(详细辅助揭秘教程)往昔有挂1、超多福利:超高返利,...
德州微扑克辅助!微扑克俱乐部2... 德州微扑克辅助!微扑克俱乐部24小时,(Wepoke)先前有挂(详细透视黑科技教程);科技详细教程Q...