简体   繁体   中英

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

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

Redirect in login service if credentials match

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM