简体   繁体   中英

Angular routing not work correctly with lazy loading

In my Angular application, when I open link localhost:4200 (application serve on it), I want that my application redirect me on localhost:4200/notes. And I want to see data of notes-component, which is contained in main component.

Example (text in html page):

App component
Main component
Notes-page component

But I only can see localhost:4200 (without redirect) and data of notes-component, without main component.

Example (text in html page):

App component
Notes-page component 

Why it works like this? And how I can correct it?

Files structure:

/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

Files:

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>

Check this out: - app.routing.ts file should have MainComponent imported here and imported in 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'
        }
    ]
  }
]);

You don't need main.module.ts

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM