如何使用BehaviourSubject Angular强制数据服务返回由next()设置的最后一个值

时间:2019-01-19 12:59:03

标签: angular rxjs behaviorsubject

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

userService

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;
  }
}

appModule

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()中设置最新值,但是我总是得到空值。

1 个答案:

答案 0 :(得分:1)

您正在尝试从订阅而不是从守卫那里返回true。您的警卫总是返回假。 CanActivate可以返回也可观察的结果,最终可以解析为完全符合您情况的布尔值:

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