我一直在构建一个Angular 2应用程序,它的设置使得如果我将用户导航到另一条路由作为第二个参数的登录路由,用户将在登录后重定向到该路由。
因此,例如,用户尝试导航到路线/客户,但他们的登录已过期。我使用后卫将它们重定向到/ login / customer,然后登录,然后重定向回/ customer。这对我的警卫很有用,但试图在我的组件中使用它会导致问题。
问题是我的组件内部似乎无法获得当前路径。
我尝试过两种方法,都使用ActivatedRoute并且都返回一个空字符串。
场景:用户位于/ customer路径上并单击以添加新客户。 API返回一个错误,指出请求是使用过期的令牌进行的。然后我需要如上所述调用router.navigate
,这意味着我需要确定当前路由(/ customer)以将其包含在导航中。
constructor(
private activatedRoute: ActivatedRoute,
private authService: AuthService,
private router: Router;
) { }
private addCustomer(customer): void {
return this.authService.post(API.CUSTOMER, customer)
.mergeMap( ... )
.catch(error => {
this.router.navigate(['/login', this.activatedRoute.snapshot.url[0].path]); // This is very simple and I like it but url is always an empty array.
return this.activatedRoute.url
.map(segments => {
this.router.navigate(['/login', segments.join('')]); // I just get and empty string from this.
});
});
}
答案 0 :(得分:0)
我能够使用vanilla javascript轻松实现这一目标。
this.router.navigate(['/login', window.location.pathname]);