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 能够正确地检查用户的授权状态。

相关内容

热门资讯

透视系统!aapoker辅助怎... 透视系统!aapoker辅助怎么用(透视)脚本(一贯是有挂);1、下载好aapoker辅助怎么用辅助...
透视透视!aapoker脚本(... 透视透视!aapoker脚本(透视)万能辅助器(确实真的是有挂)aapoker脚本辅助器中分为三种模...
透视辅助!aapoker发牌逻... 透视辅助!aapoker发牌逻辑(透视)插件下载(果然是有挂);1)aapoker发牌逻辑辅助挂:进...
透视最新!aapoker ai... 透视最新!aapoker ai插件(透视)插件下载(果然有挂);透视最新!aapoker ai插件(...
透视代打!aapoker ai... 透视代打!aapoker ai插件(透视)ai插件(果然真的是有挂)aapoker ai插件是一种具...
透视辅助!aapoker透视脚... 透视辅助!aapoker透视脚本下载(透视)万能辅助器(竟然是真的有挂)1、进入游戏-大厅左侧-新手...
透视计算!aapoker插件下... 透视计算!aapoker插件下载(透视)插件(都是是真的有挂)运aapoker插件下载辅助工具,进入...
透视软件!aapoker辅助工... 透视软件!aapoker辅助工具安全吗(透视)透视方法(总是存在有挂)1、实时aapoker辅助工具...
透视挂!aapoker插件(透... 透视挂!aapoker插件(透视)透视脚本(真是是真的有挂)亲,关键说明,aapoker插件赛季回归...
透视实锤!aapoker透视插... 透视实锤!aapoker透视插件(透视)脚本(好像真的有挂)1、每一步都需要思考,不同水平的挑战会更...