【问题标题】:Routing to a specific page within a lazy-loaded module in angular 2+以角度 2+ 路由到延迟加载模块中的特定页面
【发布时间】:2017-06-12 02:25:33
【问题描述】:

我的主应用路由器中有以下内容:

{ path: 'users', loadChildren: 'app/modules/users/users.module#UsersModule', canLoad: [AuthGuard] }

当用户转到http://localhost:4200/users/1234 查看他们的个人资料时,我会尝试保存完整的网址(包括上面的用户 ID),以便在他们登录后返回该页面。

问题是,canLoad函数中的Route参数只有一个path字段,不包含上面的用户ID,只有路径users。有什么办法可以实现吗?

第一次评论后编辑

用户路由模块确实有一个canActivate 保护,但是除了登录组件之外,它永远不会被调用,因为第一个canLoad 返回 false 并将调用者路由到登录组件。

第一次回答后编辑

canLoad(route: Route) {
  if (!AuthService.isAuthenticated()) {
    this.router.events.takeWhile(event => !(event instanceof NavigationCancel))
      .subscribe(event => {
        console.log(event);
        if (event instanceof NavigationCancel) {
          AuthService.setRedirectUrl(event.url);
        }
      });
    return false;
  }
  return true;
}

所以我尝试了上述方法,但我认为我仍然做错了,因为控制台从不记录......我如何在设置存储重定向 URL 后取消订阅或停止接收 NavigationCancel 事件?

【问题讨论】:

  • 如果你想将状态保存在守卫中,请尝试使用canActivate守卫。由于在构建路由器状态期间调用了canLoad,并且在之后调用了canActivate,因此canActivate守卫获得了更多信息。它获取激活的路由和整个路由器状态,而 canLoad 守卫只获取路由。
  • 当然可以,但是如果 canLoad 首先失败,canActivate 将永远不会被调用!
  • 对,但是如果失败了,还需要保存页面吗?
  • canLoad 失败,因为调用者没有登录。调用者然后被路由到登录组件,在验证后,应该将用户路由到原始 URL。
  • 尝试将路由器注入警卫,订阅警卫events并监听NavigationStartRoutesRecognized事件

标签: angular angular-routing angular-router-guards


【解决方案1】:

由于canLoad 在构建路由器状态期间被调用,它不会获得激活路由和整个路由器状态。它只获取路线。

您可以将路由器注入警卫,订阅NavigationCancel 事件,您可以访问该 URL。

我如何取消订阅或停止接收 NavigationCancel 事件后 设置存储重定向 URL?

由于router.events is a Subject,您可以这样退订:

// get the subscription reference
const subscription = this.router.events.takeWhile(event => !(event instanceof NavigationCancel))
      .subscribe(event => {
        console.log(event);
        if (event instanceof NavigationCancel) {
          AuthService.setRedirectUrl(event.url);
          // use it to unsubscribe
          subscription.unsubscribe(); <----------------------------
        }
      });

【讨论】:

  • 谢谢,我也编辑了我的答案,我相信仍然缺少一些东西,但我想在这种情况下它与我的可观察运算符有关!
  • @Sammy,用退订食谱更新了我的答案
猜你喜欢
  • 2020-07-12
  • 1970-01-01
  • 1970-01-01
  • 2018-05-22
  • 2019-04-03
  • 2021-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多