In this post I’ll show you how to redirect a user back to their originally requested url / route after logging into an Angular 2 application, this is done with the help of an Auth Guard and a Login Component.
Angular 2 Auth Guard
Guards in Angular 2 are used to protect routes, there are a few different guard types depending on the specific behaviour you want to implement, in this example I’m using a CanActivate guard which implements a single canActivate() method that enables you to check if a route can be activated or not, which in this case is if the user is authenticated or not.
If the user isn’t authenticated, the auth guard also redirects them to the ‘/login’ route and includes the original (previous) url in the ‘returnUrl’ parameter. The original url is accessible in the auth guard via the ‘state: RouterStateSnapshot’ parameter that is passed to the canActivate() method.
Auth Guard that passes original URL to login component
Angular 2 Login Component
The login component is a standard Angular 2 ‘controller’ component that implements the behaviour for a login form.
In the ngOnInit() method the component gets the original url that was passed from the Auth Guard as a route parameter and stores it in the local returnUrl property, if the original url is empty the returnUrl defaults to the home page route (‘/’). Parameters for the current route are accessible via the ‘private route: ActivatedRoute’ property that’s injected in the component constructor.
In the login() method the component uses the authenticationService to authenticate the username and password, on successful login the user is redirected to the returnUrl. For more details on the authentication service go to the user registraion and login example link at the top of the post.
Login Component that redirects to the previous / original URL after login
About the author