首页 > 解决方案 > 角度路由在延迟加载时无法正常工作

问题描述

在我的 Angular 应用程序中,当我打开链接 localhost:4200(应用程序在其上服务)时,我希望我的应用程序将我重定向到 localhost:4200/notes。我想查看包含在主组件中的笔记组件的数据。

示例(html页面中的文本):

App component
Main component
Notes-page component

但是我只能看到 localhost:4200 (没有重定向)和 notes-component 的数据,没有 main 组件。

示例(html页面中的文本):

App component
Notes-page component 

为什么它会这样工作?我该如何纠正它?

文件结构:

/app
  /containers
    /main
      /notes-page
        notes-page.routing.ts
        notes-page.component.ts
        notes-page.module.ts
    main.routing.ts
    main.component.ts
    main.module.ts
  app.routing.ts
  app.component.ts
  app.module.ts

文件:

app.routing.ts

export const routing: ModuleWithProviders = RouterModule.forRoot([
  {
    path: '',
    loadChildren: './containers/main/main.module#MainModule'
  }
]);

app.component.html

<h5>App component</h5>
<router-outlet></router-outlet>

主模块.ts

export const routing: ModuleWithProviders = RouterModule.forChild([
  {
    path: '',
    component: MainComponent,
    children: [
      {
        path: '',
        redirectTo: 'notes',
        pathMatch: 'full'
      },
      {
        path: 'notes',
        loadChildren: './notes-page/notes-page.module#NotesPageModule'
      }
    ]
  }
]);

main.component.html

<h5>Main component</h5>
<main> 
  <router-outlet></router-outlet>
</main> 

笔记-page.module.ts

export const routing: ModuleWithProviders = RouterModule.forChild([
  {
    path: '',
    pathMatch: 'full',
    component: NotesPageComponent
  }
]);

注释-page.component.html

<h5>Notes-page component</h5>

标签: javascriptangularrouting

解决方案


检查一下: - app.routing.ts 文件应该在此处导入 MainComponent 并在 app.module.ts 中导入:

export const routing: ModuleWithProviders = RouterModule.forRoot([
  {
    path: '',
    component: MainComponent,
    children: [
        { path: '', redirectTo: 'notes', pathMatch: 'full'},
        {
          path: 'notes',
          loadChildren: './notes-page/notes-page.module#NotesPageModule'
        }
    ]
  }
]);

你不需要 main.module.ts


推荐阅读