【问题标题】:Delay the route canActivate method call till backend service return result in angular 7延迟路由 canActivate 方法调用,直到后端服务返回角度 7
【发布时间】:2019-12-14 14:18:20
【问题描述】:

需要延迟路由 canActivate 方法调用,直到我的身份验证服务返回用户 ID 的用户角色。

我们的 Angular 应用程序没有任何登录页面,它使用来自服务器登录的用户 ID。 当用户访问 URL 时,在 app.compoment.ts 中调用身份验证服务,但在服务返回任何结果之前,调用 canActivate 方法,并且当时没有用户角色。所以阻止所有用户访问。

我曾尝试使用异步并等待 https 调用来获取用户数据,但这也不起作用。 有人可以帮忙吗?

【问题讨论】:

  • 用您的 canActivate 和您的身份验证服务的源代码更新问题。
  • 在守卫中进行服务调用,您可以从 canActivate 中返回一个 boolean observable。

标签: angular https async-await angular-ui-router angular7-router


【解决方案1】:

这里,rxJS 的 pipe() 是有用的,不如订阅先使用 pipe()。

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>  {
    return this​.​loginService​.​isLoggedIn​().​pipe​(
        map(e => {
           if (e) {
               return true;
             } else {

             }
         }),
          catchError((err) => {
             this​.​router​.​navigate​([​'/login'​]);
             return of(false);
           })
      );
  }   

【讨论】:

  • 管道无法解决问题,我使用管道,因为管道在 Angular 7 API 调用中是强制性的。为了解决这个问题,我创建了登录页面,用户将在其中提供用户 ID,然后应用程序将路由到 SSO 登录。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多