Redirigir a un componente diferente dentro de @canActivate en Angular2


¿Hay alguna forma de redirigir a un componente diferente de @canActivate en Angular2 ?

Author: Vinz and Tonz, 2016-01-11

5 answers

¡Sí, puedes! Hacer esto evitará que su componente instancie por nada.

Primero, crea un nuevo archivo src/app-injector.ts

let appInjectorRef;

export const appInjector:any = (injector = false) => {
    if (!injector) {
        return appInjectorRef;
    }

    appInjectorRef = injector;

    return appInjectorRef;
};

Luego, obtenga la referencia de bootstrap

// ...
import {appInjector} from './app-injector';
// ...


bootstrap(App, [
  ROUTER_PROVIDERS
]).then((appRef) => appInjector(appRef.injector));

Finalmente en su función

// ...
import {appInjector} from './app-injector';
// ...

@CanActivate((next, prev) => {
  let injector = appInjector();
  let router = injector.get(Router);

  if (42 != 4 + 2) {
    router.navigate(['You', 'Shall', 'Not', 'Pass']);
    return false;
  }

  return true;
})

Et voilà !

Se discutió aquí https://github.com/angular/angular/issues/4112

Puedes encontrar un ejemplo completo aquí http://plnkr.co/edit/siMNH53PCuvUBRLk6suc?p=preview por @brandonroberts

 12
Author: Druxtan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-20 01:27:28

A partir de hoy, con la última @angular/router 3.0.0-rc.1, aquí hay un par de referencias sobre cómo hacerlo a través de CanActivate guardias en las rutas:

  1. angular 2 referencia
  2. Dos respuestas a esta pregunta, por Nilz11 y por Jason

La esencia principal de la lógica se parece a:

// ...
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
  if (this.authService.isLoggedIn) {
    // all ok, proceed navigation to routed component
    return true;
  }
  else {
    // start a new navigation to redirect to login page
    this.router.navigate(['/login']);
    // abort current navigation
    return false;
  }
}
 51
Author: superjos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:54:53

Angular 2.0 solución final:

Su guardia puede ser fácilmente un inyectable que, como tal, puede incluir sus propios inyectables. Así que podemos simplemente inyectar el router, con el fin de redirigir. No olvides agregar el servicio como proveedor en tu módulo de aplicación.

@Injectable()
export class AuthGuard implements CanActivate {

  constructor(private router: Router, private authService: AuthService) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
    if (!authService.isAuthenticated()) {
      this.router.navigate(['/login']);
      return false;
    }
    return true;
  }
}

export const ROUTES: Routes = [
  {path: 'login', component: LoginComponent},
  {path: 'protected', loadChildren: 'DashboardComponent', canActivate: [AuthGuard]}
];
 13
Author: Stephen Paul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-02 08:43:05

Esto podría ayudar a alguien que está tratando de esperar en algo antes de continuar.

waitForBonusToLoad(): Observable<[boolean, string]> {

const userClassBonusLoaded$ = this.store.select(fromRoot.getUserClasssBonusLoaded);
const userClassSelected$ = this.store.select(fromRoot.getClassAttendancesSelectedId);

return userClassBonusLoaded$.withLatestFrom(userClassSelected$)
  .do(([val, val2]) => {
    if (val === null && val2 !== null) {
      this.store.dispatch(new userClassBonus.LoadAction(val2));
    }
  })
  .filter(([val, val2]) => {
    if(val === null && val2 === null) return true;
    else return val;
  })
  .map(val => {
    return val;
  })
  .take(1);
}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.waitForBonusToLoad().map(([val, val2]) =>
  {
    if(val === null && val2 === null){
      this.router.navigate(['/portal/user-bio']);
      return false;
    }
    else {
      return true;
    }
  }
)
}
 2
Author: Helzgate,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-08 16:35:28

Si está utilizando un observable para determinar, puede aprovechar tap operador de rxjs:

@Injectable({
  providedIn: SharedModule // or whatever is the equivalent in your app
})
export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService,
              private router: Router) {}

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.authService.isLoggedIn()
      .pipe(tap((isLoggedIn: boolean) => {
        if (!isLoggedIn) {
          this.router.navigate(['/']);
        }
      }));
  }

}
 0
Author: s.alem,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-08 20:22:28