angular 5 - redirect the previous page after sign in
You can send the URL before going to the homepage and use it there
@Component({ ... })
class SomePageComponent {
constructor(private route: ActivatedRoute, private router: Router) {}
checkLogin() {
if (!this.auth.loggedIn()) {
this.router.navigate(['/homepage`], { queryParams: { redirectTo: this.route.snapshot.url } });
}
}
}
So then in your login Component you can access to the queryParams like this
@Component({...})
class LoginComponent {
constructor(private router: Router, private route: ActivatedRoute) {}
backToPreviousPage() {
this.router.navigate(
[this.route.snapshot.queryParams.get('redirectTo')]
);
}
}
FOR ANGULAR 7+
Since Angular 7.2 you could use the state object to set the last url before linking to the login page:
@Component({ ... })
class SomePageComponent {
constructor(private router: Router) {}
checkLogin() {
if (!this.auth.loggedIn()) {
this.router.navigate(['login'], { state: { redirect: this.router.url } });
}
}
}
@Component({...})
class LoginComponent {
constructor(private router: Router) {}
backToPreviousPage() {
const { redirect } = window.history.state;
this.router.navigateByUrl(redirect || '/homepage');
}
}
for me queryParams not work properly because if the user goes to log in, and next go to the signup route, so you need to preserve query params. But if you have more steps before login, or user refreshes the page, or the internet was bad on a subway or something else happened and he lost his params and will be redirected to who knows... But if you set needed URL to redirect to localStorage and after login/signup/someelse step you can redirect him to needed URL previously delete the string from localStorage.
// needed page
localStorage.setItem('redirectTo', this.router.url);
this.router.navigateByUrl('/login');
// login/signup/else step page
success => {
const redirect = localStorage.getItem('redirectTo');
if (redirect) {
localStorage.removeItem('redirectTo');
this.router.navigate(redirect);
} else {
this.router.navigate('defaultpath');
}
}
When you redirect to the login page with a guard, you could put the source url in the queryParams
as such:
canActivate(next: ActivatedRouteSnapshot,
state: RouterStateSnapshot) {
if (this.authService.isAuthenticated()) {
return true;
} else {
console.log('Could not authenticate');
this.router.navigate(['login'],{queryParams:{'redirectURL':state.url}});
return false;
}
}
After you log in you can get the original page url from the query params:
let params = this.route.snapshot.queryParams;
if (params['redirectURL']) {
this.redirectURL = params['redirectURL'];
}
...
if (this.redirectURL) {
this.router.navigateByUrl(this.redirectURL,)
.catch(() => this.router.navigate(['homepage']))
} else {
this.router.navigate(['homepage'])
}