如何在 Angular 独立组件上注册嵌套路由?

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

我需要将下面的组件/视图(带有嵌套路由)从 NgModule 迁移到独立的

用于路由的 Angular 文档未提及独立组件,并且 独立文档仅展示如何路由独立组件

@Component({
  selector: "app-account",
  templateUrl: "./account.component.html",
  styleUrls: ["./account.component.scss"],
})
export class AccountComponent {}

export const AccountRoutes: Routes = [
  {
    path: "",
    component: AccountComponent,
    children: [
      {
        path: "login",
        component: LoginComponent,
      },
      {
        path: "register",
        component: RegisterComponent,
      },
      {
        path: "confirm",
        component: ConfirmComponent,
      },
    ],
  },
];

@NgModule({
  imports: [CommonModule, RouterModule.forChild(AccountRoutes)],
  declarations: [AccountComponent, LoginComponent, RegisterComponent, ConfirmComponent],
})
export class AccountModule {}

我尝试了像下面这样的

provideRouter
,但似乎只能与
bootstrapApplication
一起使用,并出现错误:
Type 'EnvironmentProviders' is not assignable to type 'Provider'

@Component({
  selector: 'app-account',
  standalone: true,
  imports: [CommonModule, RouterOutlet],
  providers: [
    provideRouter(routes)
  ],
  templateUrl: './account.component.html',
  styleUrls: ['./account.component.scss'],
})
export class AccountComponent {}
angular angular-router angular-standalone-components
1个回答
0
投票

您可能想要实现的目标是这个;

// In the main application:
export const ROUTES: Route[] = [
  {path: 'admin', loadChildren: () => import('./admin/routes').then(mod => mod.ADMIN_ROUTES)},
  // ...
];

// In admin/routes.ts:
export const ADMIN_ROUTES: Route[] = [
  {path: 'home', component: AdminHomeComponent},
  {path: 'users', component: AdminUsersComponent},
  // ...
];

这条信息隐藏在这里:一次延迟加载多条路线

本质上,这与您延迟加载的 Angular 子模块的

loadChildren()
函数相同。但根据我的理解,这就是你所能做的。您将无法在独立组件中拥有嵌套的路由器提供程序。您只能在 AppComponent 引导时执行此操作。

这可能就是他们说的原因,

在许多

常见的延迟加载场景中,不再需要 NgModule。 1

如果您必须进行深度嵌套的延迟加载(例如在具有大型开发组的大型应用程序中),我仍然会在独立应用程序中使用 ngModule,这将使其业务逻辑与主应用程序完全隔离。

© www.soinside.com 2019 - 2024. All rights reserved.