【问题标题】:Angular routing not work correctly with lazy loading角度路由在延迟加载时无法正常工作
【发布时间】:2018-04-29 20:45:34
【问题描述】:

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

示例(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>

main.module.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> 

notes-page.module.ts

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

notes-page.component.html

<h5>Notes-page component</h5>

【问题讨论】:

  • 在此处添加 pathMatch: 'full' : path: '', loadChildren: './containers/main/main.module#MainModule'
  • 没用。
  • 但感谢您的回答

标签: javascript angular routing


【解决方案1】:

检查一下: - 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

【讨论】:

  • 不,这对我没有帮助。它像上面一样工作。不过谢谢你的回答。
  • 很抱歉听到这个消息……几个月前我遇到了同样的情况,它对我有用。它显示了来自 appcomponent、maincomponent 和 notescomponent 的数据。奇怪...
  • 至少它会将你重定向到“notes”路线吗?
  • 不,我不明白为什么,但它一直在 /。
猜你喜欢
  • 2017-10-20
  • 2016-10-24
  • 1970-01-01
  • 2019-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多