如何动态添加路由到延迟加载的模块?

问题描述 投票:0回答:1

延迟加载模块的路由配置结构不同,因为延迟加载模块有自己单独的路由配置。就我而言,我从数据库中获取了路由,并且需要在用户成功登录时将它们应用到 router.config。

核心模块在路径“core”上的应用程序模块中延迟加载。

应用程序路由.modules.ts

const routes: Routes = [
  { path: '', redirectTo: '/login', pathMatch: 'full' },
  { path: 'login', component: LoginComponent },
  { path: 'core', loadChildren: () => import('@modules/pu-core/pu-core.module').then(m => m.PuCoreModule) }
];

核心模块

const routes: Routes = [
  { path: 'layout', component: LayoutComponent, childre:[] },
];

登录成功后,auth 服务有一个可观察的

apiRoutes$
,其中包含需要应用于
layout
路径子级的路由。

使用

this.router.config
动态添加子项不起作用,因为配置不同。

以下实现不起作用:

constructor(public router: Router, private activatedRoute: ActivatedRoute, @SkipSelf() private auth: AuthService) {

    this.auth.routes$.subscribe(
      (routesData: any) => {
        this.router.config[2].children = routesData;
      }
    )
  }
angular angular-routing angular15 angular-lazyloading
1个回答
0
投票
  • 登录后更新路线: 成功登录后,您可以将 PuCoreRoutingService 注入您的身份验证服务(或处理登录成功的任何地方)并根据需要更新路由。
constructor(private puCoreRoutingService: PuCoreRoutingService) {}

onLoginSuccess(): void {
  this.auth.routes$.subscribe((routesData: Routes) => {
    this.puCoreRoutingService.updateLayoutChildrenRoutes(routesData);
  });
}
  • 核心模块中的路由更新服务: 在 PuCoreModule 中创建一个允许更新路由的服务。该服务可以有一个方法来更新 LayoutComponent 的子路由。
import { Injectable } from '@angular/core';
import { Router, Routes } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class PuCoreRoutingService {
  constructor(private router: Router) {}

  public updateLayoutChildrenRoutes(routes: Routes): void {
    const config = this.router.config;
    const layoutRoute = config.find(r => r.path === 'layout');
    if (layoutRoute) {
      layoutRoute.children = routes;
      this.router.resetConfig(config);
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.