【问题标题】:Angular 6 RXJS filter to wait for boolean value in subscriptionAngular 6 RXJS 过滤器等待订阅中的布尔值
【发布时间】:2018-08-30 14:34:26
【问题描述】:

我正在尝试检查用户是否已通过身份验证,并且我正在使用一种方法,如果用户已通过身份验证,则该方法返回 true 或 false 的 observable。我正在尝试做的是等待授权有一个值,然后在回调函数中检查它是真还是假,并根据它的值执行操作。所以基本上我不希望我的过滤器函数检查值是真还是假,而是在继续订阅回调中的代码之前检查是否有值。

这是我的功能:

this.oidcSecurityService.getIsAuthorized().pipe(filter(authorized => authorized !== undefined)).subscribe(authorized => {
  console.log(authorized);
  this.isAuthorized = authorized;
  if (!authorized) {
    debugger
    this.login()
  }
  else {
    debugger
    this.getBoSpar()
  }
});

我做错了什么,如何让过滤器功能检查是否已获取授权,而不是检查它是真还是假?我没有收到任何错误,只是授权总是被评估为假,即使我知道用户已经过身份验证(我已经分离了发生在点击事件上的逻辑,并且有效)。

【问题讨论】:

  • 我没有立即看到您的代码或逻辑有任何问题。您可以编辑您的问题以包含getIsAuthorized 的代码吗?

标签: angular rxjs observable


【解决方案1】:

authorized !== undefined 看起来不对

authorized != null 仅检查 null 和 undefined

this.oidcSecurityService.getIsAuthorized()
  .pipe(
    tap(authorized => console.log('BEFORE', authorized)),
    filter(authorized => authorized != null),
    tap(authorized => console.log('AFTER', authorized))
  )
  .subscribe(authorized => {
    console.log(authorized);
    this.isAuthorized = authorized;
    if (!authorized) {
      debugger
      this.login()
    } else {
      debugger
      this.getBoSpar()
    }
});

还值得使用 tap 来检查通过管道的值,在过滤器之前和之后。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-01
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 2017-10-08
    • 2019-03-24
    相关资源
    最近更新 更多