Angular路由器可以激活保护,如何处理实时?
创始人
2024-10-28 03:00:45
0

可以通过实现一个具有Observable输入的AuthService来解决这个问题。 在该服务中,我们将提供一个名为authState$的可观察对象,以便我们可以直接订阅和监视当前用户的身份验证状态。 我们可以将路由守卫与这个可观察对象合并,以便我们可以在任何时间点验证用户是否已经登录。

代码示例如下:

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

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private authStateSubject = new BehaviorSubject(false);
  authState$: Observable = this.authStateSubject.asObservable();

  constructor() {}

  login() {
    // perform login logic here
    // once login is successful, change the value of authStateSubject to true
    this.authStateSubject.next(true);
  }

  logout() {
    // perform logout logic here
    // once logout is complete, change the value of authStateSubject to false
    this.authStateSubject.next(false);
  }
}

现在我们有了一个AuthService,可以在 Guard 中将其注入,以便我们可以检查用户的身份验证状态:

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

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable | Promise | boolean {
    return this.authService.authState$.pipe(
      tap(authenticated => {
        if (!authenticated) {
          // if user is not authenticated, redirect them to the login page
          this.router.navigate(['/login']);
        }
      })
    );
  }
}

通过这个 Guard,我们可以确保只有当用户已经通过身份验证时才能访问受保护的路由。 另外,由于我们使用了可观察对象,因此 Guard 将在用户身份验证状态更改时自动重复验证。

相关内容

热门资讯

攻略讲解!掌中乐游戏中心有辅助... 攻略讲解!掌中乐游戏中心有辅助吗(透视)一直是有挂(2020已更新)(哔哩哔哩)1、掌中乐游戏中心有...
九分钟了解!心悦麻将软挂神器,... 九分钟了解!心悦麻将软挂神器,八闽十三张十三水有外挂吗,AI教程(有挂软件);1、很好的工具软件,可...
必备教程!wepoke打伙牌(... 必备教程!wepoke打伙牌(wepoke真的有挂)wepoke(好像真的有挂)需要回顾用户提供的搜...
教程攻略!八闽状元郎在哪里开挂... 教程攻略!八闽状元郎在哪里开挂(透视)一直是有挂(2020已更新)(哔哩哔哩)1、让任何用户在无需八...
we辅助poker德之星!we... we辅助poker德之星!wepoke软件透明,wepOke原来真的有挂,2025版教程(有挂揭秘)...
五分钟了解!掌中乐游戏中心吗,... 五分钟了解!掌中乐游戏中心吗,兴动辅助器免费版v3.0,技巧教程(有挂ai代打)1、兴动辅助器免费版...
微扑克系统发牌规律!微扑克辅助... 微扑克系统发牌规律!微扑克辅助是真的,微扑克可以加入俱乐部,揭秘攻略(有挂脚本)1、这是跨平台的微扑...
技术分享!狂飙娱乐辅助器(辅助... 技术分享!狂飙娱乐辅助器(辅助)好像真的有挂(2023已更新)(哔哩哔哩)1)狂飙娱乐辅助器辅助挂:...
七分钟了解!闲玩游戏外 挂,蛮... 七分钟了解!闲玩游戏外 挂,蛮籽麻将有没有套路,AI教程(有挂解密);暗藏猫腻,小编详细说明蛮籽麻将...
wepoke有挂!wepoke... wepoke有挂!wepoke模拟器,wepoke有挂,透明教程(有挂介绍);亲真的是有正版授权,小...