Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

284
Views
Redirigir a un componente diferente dentro de @CanActivate en Angular2

¿Hay alguna forma en que podamos redirigir a un componente diferente de @CanActivate en Angular2?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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

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

La esencia principal de la lógica se ve así:

 // ... 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; } }
over 4 years ago · Santiago Trujillo Report

0

Su guardia puede ser simplemente un inyectable que, como tal, puede incluir sus propios inyectables. Entonces, simplemente podemos inyectar el enrutador para redirigir . No olvide agregar el servicio como proveedor en el módulo de su 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]} ];
over 4 years ago · Santiago Trujillo Report

0

¡Sí tu puedes! Hacer esto evitará que su componente se cree una instancia para nada.

Primero, cree 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 voila!

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

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!