简体   繁体   中英

Can CanActivate in Angular continue after navigating to another route?

In an auth guard when authentication is missing I want to display Facebook login. Wonder if it will work to do router.navigate(['login']) in canActivate to trigger authentication and return async result of the login or will it be interrupted by the router.navigate call. Wonder about proper and simple flow here.

yes it is possible. you can also use navigateByUrl to get to facebook

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { UserService } from './user.service';

@Injectable()
export class AuthGuardService implements CanActivate {

  constructor(private userService: UserService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (this.userService.isValid()) {
      return true;
    } else {
      this.router.navigate(['/login'], {
        queryParams: {
          return: state.url
        }
      });
      return false;
    }
  }
}

code snippet credits go to / more examples can be found on : http://gnomeontherun.com/2017/03/02/guards-and-login-redirects-in-angular/

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