代码之家  ›  专栏  ›  技术社区  ›  panagulis72

使用tap()而不是map()rxjs和angular

  •  1
  • panagulis72  · 技术社区  · 7 年前

    我有一个登录保护,它基本上检查用户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;
                    }
                })
            )
    }
    

    现在,由于我不必更改或编辑输出数据(经过验证的布尔值),我想:那么,为什么不使用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;
                    }
                })
            )
    }
    

    然后我去了Chrome,我看到了黑色的页面,情况就是这样:

    无论如何,我看到的都是空白页。所以,我进入调试阶段,注意到它正确地跳转到if/else块中…那么,为什么tap()会破坏应用程序?

    2 回复  |  直到 6 年前
        1
  •  4
  •   Frederik Struck-Schøning    6 年前

    This 是的签名 canActivate :

    interface CanActivate {
      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean
    }
    

    激活 必须返回 boolean Promise . 所以你必须 map 然后返回 布尔值 承诺 . tap 不会变戏法的。

        2
  •  1
  •   Picci    7 年前

    卫兵 canActivate 必须返回 Observable<boolean> 以便角防护机构工作。

    使用 map 允许您定义一个不同于您所得到的回报 isAuthenticated 这可能解释了你所看到的。

    在你的第一个版本中 激活 准确返回 可观察布尔值 -在第二种情况下,它返回这个 this.store.select(fromApp.isAuthenticated).pipe(take(1)) 可能这不是你想要的。