路由到角度为2+的延迟加载模块中的特定页面 [英] Routing to a specific page within a lazy-loaded module in angular 2+

查看:73
本文介绍了路由到角度为2+的延迟加载模块中的特定页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following in my main app router:

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

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

When the user goes to http://localhost:4200/users/1234 to see their profile, I try to save the full url (including the user ID above) so that I would route back to that page once they're logged in.

问题是,canLoad函数中的Route参数仅具有一个path字段,该字段不包括上述用户ID,仅包括路径users.有什么办法可以做到这一点?

The problem is, the Route parameter in the canLoad function only has a path field that does not include the user ID above, only the path users. Is there a way I can achieve this?

在第一个评论后进行编辑

用户路由模块确实具有canActivate防护,但是除登录组件外,该防护从未被调用,因为第一个canLoad返回false并将调用者先前路由到登录组件.

The users routing module does have a canActivate guard, but this never gets called except from the login component, since the first canLoad returned false and routed the caller to the login component previously.

在第一个答案后进行编辑

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

So I tried the above, but I think I'm doing something wrong still, since console never logs... how do I unsubscribe or stop receiving NavigationCancel events after I set store the redirect URL?

推荐答案

由于在构造路由器状态期间调用了canLoad,因此不会获得激活的路由和整个路由器状态.它只会得到路线.

Since canLoad is called during the construction of the router state it doesn't get activated route and the whole router state. It gets only the route.

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

You can inject a router into a guard, subscribe to NavigationCancel event where you can access the URL.

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

how do I unsubscribe or stop receiving NavigationCancel events after I set store the redirect URL?

因为 router.events是主题,您可以这样取消订阅:

Since router.events is a Subject, you can unsubscribe from it like this:

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

这篇关于路由到角度为2+的延迟加载模块中的特定页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆