【问题标题】:Interrogation about the RxJS 5 filter() operator关于 RxJS 5 filter() 操作符的询问
【发布时间】:2017-06-26 04:32:41
【问题描述】:

我有一个 Angular 2 路由器保护器,其 canActivate 方法定义如下:

canActivate() {
    return this.sessionSigninService.isAuthenticated()
      .filter(isAuthenticated => isAuthenticated !== null)
      .map(isAuthenticated => {
        if (isAuthenticated) {
          return true;
        }
        this.router.navigate(['/signin']);
        return false;
      });
  }

来自sessionSigninService

  isAuthenticated(): Observable<boolean> {
    return this.store.select(fromRoot.getAuthenticated);
  }

仅供参考,fromRoot.getAuthenticated 被初始化为 null

当调用canActivate 方法并且isAuthenticatednull 值进入filter() 运算符时,似乎filter() 会阻塞,直到isAuthenticated 的值更改为false 或@ 987654334@.

请注意,这是期望的行为,但我不明白...

有人可以解释一下这种行为吗?

【问题讨论】:

    标签: rxjs rxjs5 ngrx


    【解决方案1】:

    与 Array.prototype.filter() 一样,它仅在通过标准函数时才从源发出值。

    filter 只会在过滤器方法的返回值为 true 时传播数据 - 当您有 isAuthenticated: null 并评估 null !== null -> 它将返回 false,这就是不传播数据的原因并且不会调用map

    一旦您拥有isAuthenticated: true|false,过滤器将评估为true,因为truefalse 都是!== null,并传播数据。

    【讨论】:

    • 感谢 olsn。为了描述这种行为,正确的 RxJS 术语是什么?只要谓词不评估为真,filter 运算符 blocks 是否正确?
    • 我会选择运营商的名字并说“filters out”——“blocks”这个词对我来说听起来像数据可能会在稍后的时间点解除阻塞,但事实并非如此,数据只是“消失”
    猜你喜欢
    • 2023-03-23
    • 2016-05-10
    • 2017-04-28
    • 2021-02-12
    • 2013-02-27
    • 2021-04-21
    • 1970-01-01
    • 2016-11-06
    • 2021-12-01
    相关资源
    最近更新 更多