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

423
Views
Angular: cómo enrutar diferentes módulos en la misma ruta según el servicio

Imagine un servicio ABService con un método isAResponsible: () => boolean y dos módulos: AModule y BModule .

La pregunta es: ¿Es posible cambiar entre AModule y BModule dependiendo de lo que devuelva isAResponsible ? ¿Y cómo 'redireccionamos' y volvemos a renderizar si cambia el valor de isAResponsible ? ABService puede tener varias dependencias con otros servicios, por lo que sería preferible hacer uso del sistema DI de alguna manera.

Ejemplo: si la ruta de interés es /aorb y ABService.isAResponsible devuelve true , entonces nos gustaría enrutar AModule . Si ABService.isAResponsible devuelve false , sin embargo, queremos que BModule administre el enrutamiento adicional. Tenga en cuenta que todo debería suceder en una ruta compartida .

Lo probé con guardias y canActivate / canLoad pero no tuve éxito:

aplicación.módulo.ts

 import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { AorBActivateGuard } from './aorb-activate.guard'; import { ABService } from './ab.service'; @NgModule({ imports: [ BrowserModule, RouterModule.forRoot([ { path: 'aorb', canActivate: [AorBActivateGuard], loadChildren: () => import('./a/a.module').then((m) => m.AModule), }, { path: 'aorb', loadChildren: () => import('./b/b.module').then((m) => m.BModule), }, ]), ], providers: [AorBActivateGuard, ABService], declarations: [AppComponent], bootstrap: [AppComponent], }) export class AppModule {}

ab.service.ts

 import { Injectable } from '@angular/core'; @Injectable() export class ABService { private aIsResponsible = true; constructor() {} switch() { this.aIsResponsible = !this.aIsResponsible; } isAResponsible() { return this.aIsResponsible; } }

aorb-activate.guard.ts

 import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, } from '@angular/router'; import { Observable } from 'rxjs'; import { ABService } from './ab.service'; @Injectable() export class AorBActivateGuard implements CanActivate { constructor(private abService: ABService) {} canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<boolean> | Promise<boolean> | boolean { return this.abService.isAResponsible(); } }
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Uno puede inyectar ABService en AppModule y escuchar los cambios de ABService . Cada vez que ocurre un cambio, podemos reconfigurar (= cambiar módulos) el enrutador y dejar que navegue por la misma ruta. De esta forma siempre tenemos cargado el módulo responsable.

 [...] @NgModule({ imports: [ BrowserModule, RouterModule.forRoot([], { initialNavigation: 'disabled', }), ], providers: [ABService, BooleanStorageService], declarations: [AppComponent], bootstrap: [AppComponent], }) export class AppModule { constructor(private router: Router, private abService: ABService) { abService.onABChange.subscribe(this.resetRouterConfig(true).bind(this)); this.resetRouterConfig(false)(); this.router.initialNavigation(); } reloadCurrentRoute() { const currentUrl = this.router.url; this.router.navigateByUrl('/', { skipLocationChange: true }).then(() => { this.router.navigate([currentUrl]); }); } resetRouterConfig(refresh: boolean) { return () => { const constructedConfig = [ { path: '', pathMatch: 'full', redirectTo: 'aorb', }, { path: 'aorb', loadChildren: () => { if (this.abService.isAResponsible()) { return import('./a/a.module').then((m) => m.AModule); } else { return import('./b/b.module').then((m) => m.BModule); } }, }, ]; this.router.resetConfig(constructedConfig); if (refresh) this.reloadCurrentRoute(); }; } }

Puede encontrar un ejemplo de trabajo aquí .

over 4 years ago · Santiago Trujillo Report

0

Puede probar esto en su lugar, acabo de verificar localmente que funciona, solo piénselo de una manera diferente y tendrá su solución :)

 import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { AorBActivateGuard } from './aorb-activate.guard'; import { ABService } from './ab.service'; @NgModule({ imports: [ BrowserModule, RouterModule.forRoot([ { path: 'aorb', loadChildren: () => { if ((new ABService()).isAResponsible()){ return import('./a/a.module').then((m) => m.AModule) } else { return import('./b/b.module').then((m) => m.BModule) } }, }, ]), ], providers: [AorBActivateGuard, ABService], declarations: [AppComponent], bootstrap: [AppComponent], }) export class AppModule {}
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!