Angular 如何使用Behavior()强制dataservice返回上一个值集

Angular 如何使用Behavior()强制dataservice返回上一个值集,angular,rxjs,behaviorsubject,Angular,Rxjs,Behaviorsubject,我正在写申请表。用户登录我的AuthService后,我使用next()更改我的userService中Behavior Subject变量的值。在我的GuardService中,我想从变量中获取最新的值,但我总是获取初始值 用户服务 export class UserService { private isAdmin = new BehaviorSubject<boolean>(true); isCurrentUserAdmin = this.isAdmin.asObservab

我正在写申请表。用户登录我的AuthService后,我使用next()更改我的userService中Behavior Subject变量的值。在我的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);
  }
}
应用模块

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的observable中的响应在UserService.changeAdminRole()中设置了最新的值,当从我的AuthService调用时,但我总是得到null。

您试图从subscribe返回
true
,而不是从guard返回。你的卫兵总是假动作。还可以返回observable,最终解析为完全适合您的情况的布尔值:

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

我认为
canActivate
是实现
canActivate(下一步:ActivatedRouteSnapshot,state:routerstatesapshot):可观察的| Promise | boolean
这不是答案我只是确定代码
canActivate() {
  return this.userService.isCurrentUserAdmin;
}