使用 Angular2,如何在登录重定向前重定向到上一个 url [英] Using Angular2, how to redirect to previous url before login redirect

查看:30
本文介绍了使用 Angular2,如何在登录重定向前重定向到上一个 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using Angular2 to create a single page app, I'm intercepting unauthenticated user access to non-public routes in a custom RouterOutlet and redirecting them to a login view. After a successful login, I want to redirect the user to their originally requested view, rather than the default view.

我注意到 Router 有一个 renavigate() 函数,可以导航到最后一条成功的路线,但最后一条成功的路线是 /auth/login 而不是最初请求的网址.

I've noticed that Router has a renavigate() function that navigates to the last successful route BUT the last successful route was /auth/login and not the originally requested url.

基本上:如何访问或确定先前请求的网址?

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

I don't really want to resort to passing query string parameters around, unless I really have to. Ideally it would be nice to have access to history collection as part of the Router component, similar to backbone.history!

推荐答案

  1. 使用身份验证保护(实现 CanActivate) 以防止未经身份验证的用户.请参阅带有示例的官方文档此博客.
  2. 使用 RouterStateSnapshot用于捕获请求的 URL 的身份验证保护.

  1. Use Auth Guards (implements CanActivate) to prevent unauthenticated users. See official documentation with examples and this blog.
  2. Use RouterStateSnapshot in the auth guard to capture the requested URL.

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) 
{
    // keep the attempted URL for redirecting
    this._loginService.redirectUrl = state.url;
}

  • 使用 路由器(例如在 login.component.ts 中).例如.this._router.navigateByUrl(redirectUrl);

  • Redirect to that URL on successful authentication with using Router (e.g. in the login.component.ts). E.g. this._router.navigateByUrl(redirectUrl);

    附言@MichaelOryl 和 @Vitali 的建议可行,但我的方式更符合 Angular2 最终版本.

    P.S. Suggestions of @MichaelOryl and @Vitali would work, but my way is more aligned with Angular2 final release.

    这篇关于使用 Angular2,如何在登录重定向前重定向到上一个 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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