Jon*_*les 16 redirect angular2-routing angular
使用Angular2创建单页面应用程序,我将拦截未经身份验证的用户访问自定义中的非公共路由RouterOutlet
并将其重定向到登录视图.成功登录后,我想将用户重定向到最初请求的视图,而不是默认视图.
我注意到Router
有一个renavigate()
导航到最后一条成功路线的功能,但最后一条成功的路线是,/auth/login
而不是最初请求的网址.
基本上:我如何访问或确定以前请求的URL?
我真的不想求助于传递查询字符串参数,除非我真的需要.理想情况下,访问history
集合作为Router
组件的一部分会很好,类似于backbone.history
!
Ale*_*aus 18
在auth guard中使用RouterStateSnapshot捕获请求的URL.
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot)
{
// keep the attempted URL for redirecting
this._loginService.redirectUrl = state.url;
}
Run Code Online (Sandbox Code Playgroud)使用Router(例如在login.component.ts
)中成功进行身份验证后重定向到该URL .例如this._router.navigateByUrl(redirectUrl);
PS @MichaelOryl和@Vitali的建议可行,但我的方式更符合Angular2的最终版本.
您可能会在课程的文档中找到所需内容Location
.该back()
功能可能会为您做到这一点.
另一种方法是订阅popstate
事件Location
. MDN的文档讨论了您可能期望获得的价值观.
class MyCLass {
constructor(private location: Location) {
location.subscribe((val) => {
// do something with the state that's passed in
})
}
}
Run Code Online (Sandbox Code Playgroud)
否则,您可能需要一种跟踪路由器中的更改的服务,以便您可以访问它们.
class MyTrackingService {
constructor(private router: Router) {
router.subscribe((val) => {
// store the routes here so that you can peel them off as needed?
})
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我正在访问该Router
对象并订阅任何更改,以便我可以跟踪它们.
这对我有用。将其注入已在bootstrap方法中注册的主App组件的构造函数中。第一次val
在页面加载应该是原来的URL。我想立即取消订阅以提高效率,因为我(也许还)不想监听此服务中的后续路由器事件。将服务注入其他需要originalUrl的地方。
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';
@Injectable()
export class UrlTrackingService {
public originalUrl: string;
constructor(
private router: Router
) {
let subscription: Subscription = this.router.events.subscribe((val) => {
this.originalUrl = val.url;
subscription.unsubscribe();
});
}
}
Run Code Online (Sandbox Code Playgroud)