4

Context

I am loading a configuration from the server api and assign the new routes to the router, by using resetConfig and APP_INITIALIZER, (e.g. here: Angular load routing from REST service before initialization).

Inside the configuration, there are a few routes that load another module, such as:

// routes
[
    // .. some route definitions here
    { 
        path: 'my-lazy-url-path',
        loadChildren: () => import( '../my/lazy.module' ).then( m => m.LazyModule )
    },
    // ... more route definitions here
]

This is all working fine.

The routes config inside the lazy.module.ts looks as follows:

const routes: Routes = [
    {
        path: '',
        component: LazyModuleRootComponent,
        children: [
            {
                path: '',
                component: LazyModuleRootComponent,
            },
            {
                path: 'a-child-route',  // <-- I wand to change this
                component: LazyModuleChildComponent
            }
        ]
    },
    {
        path: 'slug/:param',  // <-- I want to change this
        component: SingleThingComponent,
    }

];

@NgModule( {
    imports: [
        RouterModule.forChild( routes )
    ],
    exports: [
        RouterModule
    ]
} )
export class LazyModule {
}

The Problem

Now I would like to reset the routes inside the lazy loaded module. Therefore, I am subscribing to the RouteConfigLoadEnd-event, since this is fired whenever a lazy loaded module gets loaded.

app.module.ts

export class AppRoutingModule {
    constructor( private router: Router ) {
        this.router.events.pipe(
            filter( e => e instanceof RouteConfigLoadEnd )
        ).subscribe( ( e ) => {
            // How can I reset the routes configuration for a specific module here?
            // I tried the following, but it is not working:
            setTimeout( () => {
                // the index 4 here points to the lazy route inside the main routes config
                ( this.router.config[ 4 ] as any )._loadedConfig.routes[ 1 ].path.replace( 'slug/:param', 'another-slug/:a-param' )
        }, 0 );


        } );
    }

}

How can I solve this?

uruk
  • 1,094
  • 2
  • 14
  • 26

1 Answers1

0

As I understand there is no way to reset configs of lazy modules only whole app router config like this

constructor(private router: Router) {
  this.router.events.pipe(
            filter( e => e instanceof RouteConfigLoadEnd )
        ).subscribe( ( e ) => {
             router.resetConfig({
                 ...router.config['_loadedConfig'],
                 { path: 'lazy', loadChildren: () => import(Module).then(m => m.Module)
             });
        })

}

Not sure if you have to do something like this.router.navigate('lazy') after reset. I guess that it's also possible to do reset in some guard like canActivateChild where you'll get ActivatedRouteSnapshot and it's config

Tomas
  • 471
  • 7
  • 10