Reputation: 24689
I have an angular 2 router guard whose canActivate
method is defined as follows:
canActivate() {
return this.sessionSigninService.isAuthenticated()
.filter(isAuthenticated => isAuthenticated !== null)
.map(isAuthenticated => {
if (isAuthenticated) {
return true;
}
this.router.navigate(['/signin']);
return false;
});
}
from sessionSigninService
:
isAuthenticated(): Observable<boolean> {
return this.store.select(fromRoot.getAuthenticated);
}
FYI, fromRoot.getAuthenticated
is initialized with a value of null
When the canActivate
method is called and a null
value for isAuthenticated
enters into the filter()
operator, it seems the filter()
blocks until the value of isAuthenticated
changes to false
or true
.
Note that this is the desired behavior but I don't understand it...
Can someone please explain this behavior?
Upvotes: 0
Views: 43
Reputation: 16892
Like Array.prototype.filter(), it only emits a value from the source if it passes a criterion function.
filter
will only propagate data when the returned value of the filter-method is true
- when you have isAuthenticated: null
and evaluate null !== null
-> it will return false
, that's why no data is propagated and the map
will not be called.
As soon as you have isAuthenticated: true|false
, the filter will evaluate to true
, because both true
and false
are !== null
, and propagate data.
Upvotes: 1