Angular 5 redirect to previous page after sign in.
When I am hitting a url manually, if it is not logged in, it will redirect to login page but after login, it should redirect to url which entered but now I just can redirect to homepage by using this:
this.router.navigate(['/homepage']);
Have some ideas?
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'])
}