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 将在用户身份验证状态更改时自动重复验证。

相关内容

热门资讯

透视代打!aapoker有脚本... 透视代打!aapoker有脚本吗,wpk辅助哪里买,2025新版(本来是真的有挂);原来确实真的有挂...
透视模拟器!wepoker辅助... 1、透视模拟器!wepoker辅助下载,德普之星有辅助软件吗,德州教程(从前存在有挂)(UU pok...
透视教学!wpk辅助工具,安装... 透视教学!wpk辅助工具,安装不了wepoker,解密教程(固有是真的有挂);人气非常高,ai更新快...
透视辅助!wepoker透视脚... 透视辅助!wepoker透视脚本,werplan怎么透视,2025新版技巧(固有真的是有挂)准备好在...
透视肯定!hhpoker辅助软... 透视肯定!hhpoker辅助软件,wepoker免费脚本弱密码,高科技教程(原生真的是有挂)关于hh...
透视工具!红龙poker有辅助... 透视工具!红龙poker有辅助吗,hhpoker免费辅助器,揭秘教程(真是存在有挂)需要回顾用户提供...
透视软件!wepoker辅助器... 透视软件!wepoker辅助器是真的的吗,aapoker辅助软件合法吗,透明挂教程(一向真的是有挂)...
透视攻略!wpk透视脚本,来玩... 1、透视攻略!wpk透视脚本,来玩德州破解器,曝光教程(本来是真的有挂)。2、wpk透视脚本透视辅助...
透视最新!红龙poker透视,... 透视最新!红龙poker透视,wepoker辅助透视软件,专业教程(先前真的是有挂)1、不需要AI权...
透视数据!wepoker辅助器... 1、透视数据!wepoker辅助器怎么用,wepokerplus外挂,科技教程(其实是真的有挂)。2...