【发布时间】:2017-06-13 17:42:30
【问题描述】:
我一直在构建一个 Angular 2 应用程序,它的设置是这样的,如果我将用户导航到登录路由,并使用另一个路由作为第二个参数,用户将在登录后被重定向到该路由。
例如,用户尝试导航到路线 /customer 但他们的登录已过期。我使用警卫将他们重定向到/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.
});
});
}
【问题讨论】: