如何在使用Angular2时重定向到登录重定向之前的上一个url
如何在使用Angular2时重定向到登录重定向之前的上一个url
使用Angular2创建单页面应用程序时,我在自定义RouterOutlet
中拦截非公共路由的未经身份验证的用户访问,并将其重定向到登录视图。成功登录后,我想将用户重定向到其原始请求的视图,而不是默认视图。
我注意到Router
具有renavigate()
函数,它导航到上一个成功的路由,但上一个成功的路由是 / auth / login
而不是最初请求的网址。
基本上:我如何访问或确定先前请求的url?
我真的不想使用查询字符串参数,除非我真的必须这样做。理想情况下,作为Router
组件的一部分,可以访问history
集合,类似于backbone.history
!
admin 更改状态以发布 2023年5月24日
你可能会在Location
类的文档中找到需要的内容。 back()
函数可能可以帮助您实现这一点。
另一种方法是订阅Location
中的popstate
事件。 MDN有文档,介绍了您可能会收到的数值。
class MyCLass { constructor(private location: Location) { location.subscribe((val) => { // do something with the state that's passed in }) } }
否则,您可能需要一个服务来跟踪Router的更改,以便您可以访问它们。
class MyTrackingService { constructor(private router: Router) { router.subscribe((val) => { // store the routes here so that you can peel them off as needed? }) } }
在这种情况下,我正在访问Router
对象,并订阅任何更改,以便我可以跟踪它们。
- 使用认证守卫(实现CanActivate接口)防止未经身份验证的用户。参见官方文档和示例以及本博客。
-
在认证守卫中使用RouterStateSnapshot来捕获请求的URL。
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { // keep the attempted URL for redirecting this._loginService.redirectUrl = state.url; }
-
在成功身份验证后使用Router(例如在login.component.ts中)将重定向到该URL。例如:
this._router.navigateByUrl(redirectUrl);
P.S. Michael Oryl和Vitali的建议可行,但我这种方法更符合Angular2最终版本。