首页 文章

以角度2路由到延迟加载模块中的特定页面

提问于
浏览
1

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

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

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

问题是, canLoad 函数中的 Route 参数只有一个不包含上述用户ID的 path 字段,只有路径 users . 有没有办法实现这个目标?

EDIT AFTER FIRST COMMENT

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

EDIT AFTER FIRST ANSWER

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 事件?

1 回答

  • 1

    由于_1126749_在构建路由器状态期间被调用,因此它不会被激活路由和整个路由器状态 . 它只获得路线 .

    您可以将路由器注入防护,订阅NavigationCancel事件,您可以在其中访问URL .

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

    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(); <----------------------------
            }
          });
    

相关问题