首页 > 解决方案 > Angular 10:如何在延迟加载的功能模块中重置 RouterConfig

问题描述

语境

我正在从服务器 api 加载配置并使用 and 将新路由分配给路由器resetConfigAPP_INITIALIZER例如这里:Angular load routing from REST service before initialization)。

在配置内部,有一些路由会加载另一个模块,例如:

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

这一切都很好。

lazy.module.ts中的路由配置如下所示:

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 {
}

问题

现在我想重置延迟加载模块中的路由。因此,我订阅了RouteConfigLoadEnd-event,因为每当加载延迟加载的模块时都会触发该事件。

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 );


        } );
    }

}

我该如何解决这个问题?

标签: angularmoduleconfigurationrouteslazy-loading

解决方案


推荐阅读