关于 RxJS 5 filter() 运算符的询问
Interrogation about the RxJS 5 filter() operator
我有一个 angular 2 router guard,其 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
方法并且 isAuthenticated
的 null
值进入 filter()
运算符时,filter()
似乎会阻塞,直到isAuthenticated
的值更改为 false
或 true
。
请注意,这是期望的行为,但我不明白...
有人可以解释一下这种行为吗?
Like Array.prototype.filter(), it only emits a value from the source if it passes a criterion function.
filter
只会在 filter-method 的 returned 值为 true
时传播数据 - 当您有 isAuthenticated: null
并评估 null !== null
-> 它将 return false
,这就是为什么没有数据被传播并且 map
不会被调用的原因。
只要您有 isAuthenticated: true|false
,过滤器就会评估为 true
,因为 true
和 false
都是 !== null
,并传播数据.
我有一个 angular 2 router guard,其 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
方法并且 isAuthenticated
的 null
值进入 filter()
运算符时,filter()
似乎会阻塞,直到isAuthenticated
的值更改为 false
或 true
。
请注意,这是期望的行为,但我不明白...
有人可以解释一下这种行为吗?
Like Array.prototype.filter(), it only emits a value from the source if it passes a criterion function.
filter
只会在 filter-method 的 returned 值为 true
时传播数据 - 当您有 isAuthenticated: null
并评估 null !== null
-> 它将 return false
,这就是为什么没有数据被传播并且 map
不会被调用的原因。
只要您有 isAuthenticated: true|false
,过滤器就会评估为 true
,因为 true
和 false
都是 !== null
,并传播数据.