如何使用 BehaviorSubject Angular 将数据服务强制为 return 使用 next() 设置的最后一个值

How to force dataservice with BehaviourSubject Angular to return last value set with next()

我正在写 Angular Guards 形成我的应用程序。用户登录我的 AuthService 后,我使用 next() 更改 userService 中 BehaviourSubject 变量的值。在我的 GuardService 中,我想从变量中获取最新值,但我总是获取初始值。

用户服务

export class UserService {

private isAdmin = new BehaviorSubject<boolean>(true);
isCurrentUserAdmin = this.isAdmin.asObservable();

changeAdminRole(isAdmin: boolean) {
    // change the BehaviourSubject value
    this.isAdmin.next(isAdmin);
  }
}

AdminGuard

export class AdminGuard implements CanActivate {

  constructor(private userService: UserService) { }

  canActivate() {
    this.userService.isCurrentUserAdmin
      .subscribe((response: boolean) => {
        console.log('working here', response);
        if(response) return true;
      });

    return false;
  }
}

应用模块

app.module.ts
imports: [
    BrowserModule,
    AppRoutingModule,
    BsDropdownModule.forRoot(),
    RouterModule.forRoot([
      {path: '', component: HomeComponent},
      {path: 'products', component: ProductsListComponent, canActivate: [AuthGuard, AdminGuard]},
      {path: 'shopping-cart', component: ShoppingCartComponent},
      {path: 'my-orders', component: MyOrdersComponent, canActivate: [AuthGuard, AdminGuard]},
      {path: 'check-out', component: CheckOutComponent, canActivate: [AuthGuard, AdminGuard]},
      {path: 'order-success', component: OrderSuccessComponent, canActivate: [AuthGuard, AdminGuard]},
      {path: 'login', component: LoginComponent},
      {path: 'admin/products', component: AdminProductsListComponent, canActivate: [AuthGuard, AdminGuard]},
      {path: 'admin/orders', component: AdminOrdersListComponent, canActivate: [AuthGuard, AdminGuard]},
      {path: '**', component: HomeComponent}
    ])
],
  providers: [AuthService, UserService, AuthGuard, AdminGuard]

当我导航到我想要保护的路由时,我希望 AdminGuard 的可观察到的响应在从我的 AuthService 调用时在 UserService.changeAdminRole() 中设置最新值,但我总是得到空。

您正在尝试 return true 来自订阅而不是来自守卫。你的守卫总是 return 是错误的。 CanActivate 也可以 return 观察到最终解析为完全适合您情况的布尔值:

canActivate() {
  return this.userService.isCurrentUserAdmin;
}