Angular RxJs守卫等待服务的BehaviorSubject有值
创始人
2024-10-20 14:00:32
0

要在Angular中使用RxJs守卫等待服务的BehaviorSubject有值,可以使用RxJs中的操作符filter来等待BehaviorSubject的值。

下面是一个示例代码:

首先,创建一个名为AuthGuardService的守卫服务,并注入一个名为AuthService的认证服务。

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';
import { BehaviorSubject } from 'rxjs';
import { filter } from 'rxjs/operators';

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

  constructor(private authService: AuthService, private router: Router) { }

  canActivate(): Observable {
    return this.authService.isAuthenticated.pipe(
      filter(value => value !== null), // 筛选出非空值
      map(isAuthenticated => {
        if (isAuthenticated) {
          return true;
        } else {
          this.router.navigate(['/login']);
          return false;
        }
      })
    );
  }
}

然后,在AuthService中创建一个名为isAuthenticated的BehaviorSubject,并在登录成功时将其设置为true

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

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

  isAuthenticated: BehaviorSubject = new BehaviorSubject(null);

  constructor() { }

  login() {
    // 登录逻辑
    // ...

    // 登录成功后设置isAuthenticated为true
    this.isAuthenticated.next(true);
  }

}

最后,在路由模块中使用AuthGuardService作为守卫。

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuardService } from './auth-guard.service';
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: 'home', component: HomeComponent, canActivate: [AuthGuardService] },
  { path: '', redirectTo: '/home', pathMatch: 'full' }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

这样,当访问需要身份验证的路由时,守卫将等待isAuthenticated的BehaviorSubject具有非空值,然后根据其值决定是否允许访问路由。如果isAuthenticated的值为null,守卫将等待直到值发生变化。如果值为true,则允许访问路由,否则将重定向到登录页面。

相关内容

热门资讯

据通报!wepoker辅助透视... 据通报!wepoker辅助透视软件,老友地方内蒙古辅助,都是存在有辅助软件(哔哩哔哩)1、完成老友地...
据通报!wepoker插件功能... 据通报!wepoker插件功能辅助器,518互游辅助,一贯真的有辅助插件(哔哩哔哩)1)518互游辅...
现有说明如下!菠萝辅助器免费版... 现有说明如下!菠萝辅助器免费版的特点,钱塘十三水有透视功能吗,原来真的有辅助脚本(哔哩哔哩)1、许多...
记者获悉!哈糖大菠萝开挂,潮友... 记者获悉!哈糖大菠萝开挂,潮友会鱼虾蟹脚本辅助器,总是真的有辅助工具(哔哩哔哩)1、玩家可以在潮友会...
记者获悉!pokerworld... 记者获悉!pokerworld破解版下载,越乡游辅助器,本来存在有辅助教程(哔哩哔哩)1、玩家可以在...
事发当天!wepoker透视破... 事发当天!wepoker透视破解版,广东雀神智能辅助插件,果然是有辅助技巧(哔哩哔哩)广东雀神智能辅...
据统计!wpk辅助购买,新鸿狐... 据统计!wpk辅助购买,新鸿狐辅助软件是真的吗,切实是有辅助攻略(哔哩哔哩)1、新鸿狐辅助软件是真的...
据目击者称!wepoker有没... 据目击者称!wepoker有没有挂,茶馆辅助软件,真是真的是有辅助攻略(哔哩哔哩)1、下载好茶馆辅助...
记者获悉!wepoker的辅助... 记者获悉!wepoker的辅助器,新星游挂多少钱,原来真的是有辅助插件(哔哩哔哩)1、每一步都需要思...
长期以来!wepoker破解游... 长期以来!wepoker破解游戏盒子,闲来潮汕辅助,真是是有辅助攻略(哔哩哔哩)在进入闲来潮汕辅助软...