【问题标题】:Dynamically adding new routes from the server to the app-routing.module (Angular 11)从服务器动态添加新路由到 app-routing.module (Angular 11)
【发布时间】:2021-09-03 16:21:08
【问题描述】:

大家好,我正在 Angular+Node.js 上创建一个应用程序。用户需要创建新的菜单项。每个菜单项将是一个单独的页面,带有一个单独的地址,最终应动态添加到app-routing.module 中的路由数组中。自然,我也想动态地为某些路由设置某个组件。但不幸的是,似乎不可能这样做,因为所有路由都是在应用程序的初始初始化期间设置的。然后,由于某种原因,新元素被添加到这个数组中,但是路由不起作用。

我了解到的唯一添加方法是您可以在AppRoutingModule构造函数中执行以下操作。

export class AppRoutingModule {
  private routes = [];
    
  constructor(private router: Router, private service: ContactsService) {
    this.router.config.unshift(
      { path: 'test', component: SettingsPageComponent },
    );

[...]

即通过config属性,添加一些额外的路由。但即使在同一个构造函数中,如果我尝试从服务器动态加载路由,也没有任何结果。

setTimeout(() => {
  service.getContacts().subscribe(contacts => {
    this.recursionRoutes(contacts.menu);

    this.router.config.forEach((item) => {
      if (item.canActivate) {
        this.routes.forEach((route) => {
          this.router.config.push({ path: route, component: SettingsPageComponent })
        })
      }
      this.router.resetConfig(this.router.config)
    })
    console.log(this.router.config)

  })
}, 1000)

console.log(this.router.config)

虽然新元素本质上是添加到this.router.config 数组中。但是路线不是这样工作的。

当试图去该地址时,它会抛出一个错误。

this.router.resetConfig([
  { path: 'somePath', component: SomeComponent},
  ...
]);

我在这里找到了这个方法,但由于某种原因它不起作用。在初始初始化期间在AppRoutingModule 中定义的内容,然后它可以工作。其他额外添加的路由不起作用。

【问题讨论】:

  • 为什么不在模块加载时根据需要使用带有可配置路由的延迟加载?!
  • 问题是不仅需要在加载模块时添加新路由,还需要在创建时动态添加路由,例如菜单项。我以前从未这样做过,也不知道如何使用延迟加载。如果有任何示例,我将很高兴看到示例

标签: angular routes


【解决方案1】:

试试这个:

this.router.resetConfig([
 { 
    path: 'somePath', component: SomeComponent
 },
 ...this.router.config
]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-21
    • 2018-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多