gpt4 book ai didi

redirect - 使用Angular2,如何在登录重定向之前重定向到以前的网址

转载 作者:太空狗 更新时间:2023-10-29 16:57:56 24 4
gpt4 key购买 nike

使用 Angular2 创建单页应用程序,我在自定义 RouterOutlet 中拦截未经身份验证的用户对非公共(public)路由的访问,并将它们重定向到登录 View 。成功登录后,我想将用户重定向到他们最初请求的 View ,而不是默认 View 。

我注意到 Router 有一个 renavigate() 函数,它导航到最后一个成功的路由,但最后一个成功的路由是 /auth/login 而不是最初请求的 url。

基本上:我如何访问或确定之前请求的 url?

我真的不想求助于传递查询字符串参数,除非我真的必须这样做。理想情况下,作为 Router 组件的一部分访问 history 集合会很好,类似于 backbone.history!

最佳答案

  1. 使用 Auth Guards(实现 CanActivate)来防止未经身份验证的用户。参见 official documentation有例子和this blog .
  2. 使用 RouterStateSnapshot在 auth guard 中捕获请求的 URL。

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) 
    {
    // keep the attempted URL for redirecting
    this._loginService.redirectUrl = state.url;
    }
  3. 使用 Router 成功验证后重定向到该 URL (例如,在 login.component.ts 中)。例如。 this._router.navigateByUrl(redirectUrl);

附言@MichaelOryl 和@Vitali 的建议会奏效,但我的方式更符合 Angular2 最终版本。

关于redirect - 使用Angular2,如何在登录重定向之前重定向到以前的网址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34546270/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com