独立组件中子路由的导入位置

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

我正在尝试创建一个具有 2 条不同路线的页面。

我正在尝试在我的独立组件中导入

RouterModule
,但是确实得到了

类型“ModuleWithProviders”不可分配给类型“readonly any[] |输入'。

我的代码

import { CommonModule } from '@angular/common'
import { ChangeDetectionStrategy, Component } from '@angular/core'
import { RouterModule, Routes } from '@angular/router'

export const routes: Routes = [
  {
    path: 'first',
    loadComponent: () => import('./first/first.component').then((m) => m.FirstComponent),
  },
  {
    path: 'second',
    loadComponent: () => import('./second/second.component').then((m) => m.SecondComponent),
  },
]

@Component({
  selector: 'app-home',
  standalone: true,
  imports: [
    CommonModule,

    // Router
    RouterModule.forChild(routes), // Error > Type 'ModuleWithProviders<RouterModule>' is not assignable to type 'readonly any[] | Type<any>'.
  ],
  template: `<p>home works!</p>`,
  styleUrl: './home.component.css',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class HomeComponent {}

有人有想法吗?

注意

这是一个

.forChild()
,因为 HomeComponent 正在导入到
app.module.ts
中,其中具有
.forRoot()

angular router angular-standalone-components
2个回答
0
投票

你离得很近

export const routes: Routes = [
  {
    path: 'first',
    loadComponent: () => import('./first/first.component').then((m) => m.FirstComponent),
    children: [
      {
        path: 'child',
        loadComponent: () => import('./child/child.component').then((m) => m.ChildComponent),
      },
    ]
  },
  {
    path: 'second',
    loadComponent: () => import('./second/second.component').then((m) => m.SecondComponent),
    loadChildren: () => import('./lazy-children/lazy-children.routes')
  },
]

0
投票

在顶层导入 RouterModule 一次,然后根据需要延迟加载任何子路由:

// app.routes.ts (main routing document)

export const APP_ROUTES: Routes = [
    {
        path: '',
        pathMatch: 'full',
        redirectTo: APP_PATHS.FEATURE.AUTH,
    },
    // AUTH
    {
        path: APP_PATHS.FEATURE.AUTH,
        loadChildren: () =>
            import('./features/auth/auth.routes').then(
                (mod) => mod.AUTH_ROUTES
            ),
    },

// auth.routes.ts

export const AUTH_ROUTES: Routes = [
    {
        path: '',
        component: SplashComponent,
    },
    {
        path: APP_PATHS.SECTION.LOGIN,
        component: LoginComponent,
    },
    {
        path: APP_PATHS.SECTION.FORGOT_PASSWORD,
        component: ForgotPasswordComponent,
    },
    {
        path: APP_PATHS.SECTION.REGISTER,
        component: RegisterComponent,
    },
];

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