angular 5 - redirect the previous page after sign in

13,706

Solution 1

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'])
}

Solution 2

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')]
    );
  }
}

Solution 3

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');
  }
}

Solution 4

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');
  }
}

Solution 5

Declare variable in authService url: string and use that variable in your auth.gaurd.ts

      this.authService.redirectUrl = url;
      this.navigateTo("/login");
      return false;

And then code in login.ts

          if (this.authService`enter code here`.redirectUrl) {
            this.router.navigateByUrl(this.authService.redirectUrl);
          } else {
            this.router.navigateByUrl("/home");
          }
Share:
13,706
shakell
Author by

shakell

Updated on June 05, 2022

Comments

  • shakell
    shakell about 2 years

    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?

  • Barefaced Bear
    Barefaced Bear about 3 years
    As i am new in Angular, thelast code you wrote for redirecting will be present in the subscribe portion of the login api right ?