I have been building an Angular 2 application and it's set up so that if I navigate a user to the login route with another route as the 2nd parameter the user will be redirected to that route after login.
So for example the user tries to navigate to the route /customer but their login has expired. I redirect them to /login/customer using a guard, they login and are then redirect back to /customer. This works great with my guards but trying to use it in my components is causing problems.
The issue is that inside my component I seem unable to get the current path.
I've tried a couple things, both using ActivatedRoute and both return an empty string.
Scenario: The user is on the /customer route and clicks to add a new customer. The API returns an error saying the request was made with an expired token. I then need to call router.navigate
as described above, which means I need to determine the current route (/customer) to include it in the navigation.
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.
});
});
}