Moein Hosseini
Moein Hosseini

Reputation: 1596

How to redirect another component when canActivate returns false?

Hi I am using routing in angular 5 and I have a login path that uses canActivate property

can I redirect to another path when canActivate is false? I don't want user to see the login page if he/she is logged in.

here main service returns false if user is logged in

{
    path: 'login',
    component: RegisterLoginComponent,
    canActivate: [MainService]
}

Upvotes: 6

Views: 11184

Answers (2)

aryaag
aryaag

Reputation: 110

I think a better approach would be to protect your default path with a Guard and redirect to /login from there if authentication fails.

/* AuthService */
isLoggedIn(): boolean {
  // check if user is logged in
  return isUserLoggedIn;
}

/* AuthGuard */
import { Router } from '@angular/router';
import { AuthService } from './auth.service';
...
constructor(private authService: AuthService, private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
  // check if user is logged in
  const loggedIn: boolean = this.authService.isLoggedIn();
  // if not, redirect to /login
  if (!loggedIn) {
    this.router.navigate(['/login']);
  }
  return loggedIn;
}    

Note: If you want to control where you redirect to, you have access to the url that the user was trying to access under route.url. You can check its value and then navigate to specific url, instead of always to '/login'.

Here's a quick sample code that does this redirection with asynchronous code as well. https://stackblitz.com/edit/angular-async-guard-redirect?file=src%2Fapp%2Fauth-with-redirect.guard.ts

Upvotes: 4

Miran Parkar
Miran Parkar

Reputation: 1583

Redirect in login service if credentials match

 this.authService.signin(user)
  .subscribe(
    data => {

      this.router.navigateByUrl('/dashboard');
    },
    error => console.error(error)
  )

Upvotes: -1

Related Questions