pan*_*s72 2 observable rxjs redux angular rxjs6
我有一个登录保护程序,基本上可以检查用户il是否已登录。如果已登录,则跳过登录并转到主页。我编写了这段代码,并且可以正常工作:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.store.select(fromApp.isAuthenticated)
.pipe(take(1),
map(isAuthenticated => {
if (isAuthenticated) {
this.router.navigate(['/home']);
return false;
} else {
return true;
}
})
)
}
Run Code Online (Sandbox Code Playgroud)
现在,由于我不必更改或编辑输出数据(isAuthenticated布尔值),所以我想:为什么不使用tap运算符?因此,我重新编写了代码:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.store.select(fromApp.isAuthenticated)
.pipe(take(1),
HERE------> tap(isAuthenticated => { <------ HERE
if (isAuthenticated) {
this.router.navigate(['/home']);
return false;
} else {
return true;
}
})
)
}
Run Code Online (Sandbox Code Playgroud)
然后我去了Chrome,然后看到了黑页,情况就是这样:
无论如何,我都会看到空白页。因此,我进入了调试阶段,我注意到它正确地在if / else块内跳转了……那么,为什么tap()破坏了应用程序?
这是以下内容的签名canActivate:
interface CanActivate {
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean
}
Run Code Online (Sandbox Code Playgroud)
canActivate必须返回boolean或Promise。因此,您必须输入map并返回boolean或Promise。tap不会成功的