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

183
Views
¿Es posible detener la navegación del enrutador en función de alguna condición?

Soy nuevo en angular, quiero detener el enrutamiento cuando el usuario hace clic en el botón Actualizar o en el botón Atrás según alguna condición. no se si es posible si alguien sabe ayudenme

 constructor(private route: Router) { this.route.events .filter(event => event instanceof NavigationEnd) .pairwise().subscribe((event) => { if (expression === true){ // stop routing } else { // continue routing } }); }

¿Puede ser posible? Si es así, ¿cómo puedo hacer esto?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Me encontré con esta pregunta un poco después del hecho, pero espero ayudar a alguien más que venga aquí.

El candidato principal para una solución es un guardia de ruta.

Consulte aquí para obtener una explicación: https://angular.io/guide/router#candeactivate-handling-unsaved-changes

La parte relevante (copiada casi palabra por palabra) es esta implementación:

 import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; import { MyComponent} from './my-component/my-component.component'; @Injectable({ providedIn: 'root' }) export class CanDeactivateGuard implements CanDeactivate<MyComponent> { canDeactivate( component: MyComponent, route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<boolean> | boolean { // you can just return true or false synchronously if (expression === true) { return true; } // or, you can also handle the guard asynchronously, eg // asking the user for confirmation. return component.dialogService.confirm('Discard changes?'); } }

Donde MyComponent es su componente personalizado y CanDeactivateGuard se registrará en su AppModule en la sección de proveedores y, lo que es más importante, en su configuración de enrutamiento en la propiedad de matriz canDeactivate :

 { path: 'somePath', component: MyComponent, canDeactivate: [CanDeactivateGuard] },
over 4 years ago · Santiago Trujillo Report

0

La forma más fácil para mí es con SkipLocationChange en una nueva ruta para navegar de esta manera:

 if(condition === true){ const currentRoute = this.router.routerState; this.router.navigateByUrl(currentRoute.snapshot.url, { skipLocationChange: true }); // this try to go to currentRoute.url but don't change the location. }else{ // do nothing; }

is a no beautiful method but works

over 4 years ago · Santiago Trujillo Report

0

Hay otra solución que inventé y funciona:

(Para gente perezosa como yo que no quiere crear guardia para manejar esto)

 import { NavigationStart, Router } from '@angular/router';

En constructor:

 constructor(private router: Router) { router.events.forEach((event) => { if (event instanceof NavigationStart) { /* write your own condition here */ if(condition){ this.router.navigate(['/my-current-route']); } } }); }

Con suerte, no será lo suficientemente perezoso como para cambiar '/my-current-route' a la URL de su ruta.

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!