简体   繁体   中英

Lazy loading modules with routing in Angular 2

In my app I have main module and its router and submodule and its router.

Main module (and its router) has few paths like:

/login
/sign-up
/ask
etc

The submodule has lots of paths:

/countries/edit
/countries/:id
/countries/
/coutries/search
etc

I want to do lazyloading of submodule.

I do now like this:

main router:

export const routes: Routes = [
    {
        path: "login", // to sign in or to see information about current logged user
        loadChildren: "app/login/login.module"
    },
    {
        path: "sign-up", // to sing up new users
        loadChildren: "app/signup/sign-up.module"
    },
    {
        path: "home", // to see home page
        loadChildren: "app/home/home.module"
    },
    {   // directory to see, edit, search countries
        path: "countries",
        loadChildren: "app/country/country.module"
    }

The router of submodule:

{   // to see list of countries, press like and delete a country
    path: "",
    component: CountryViewAllComponent
},
{
    // CR[done] try to avoid inline comments.
    path: "search",
    component: CountrySearchComponent
},
{
    path: "edit",
    component: CountryChangeComponent,
},
{
    path: ":id",
    component: CountryDetailComponent
}

My app works perfect if I enter on main page / and after navagate by pages clicking on links. But if I reload page for example /countries/search it moves me to countries page and gives exception: "Cannot match any routes: 'search'"

You are missing pathMatch:full and check how you have used RouterModule.forChild(routes) or forRoot.. for better reference see this doc:

Lazy loading module (Angular 2 training book)

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { EagerComponent } from './eager.component';

const routes: Routes = [
  { path: '', redirectTo: 'eager', pathMatch: 'full' },
  { path: 'eager', component: EagerComponent },
  { path: 'lazy', loadChildren: 'lazy/lazy.module#LazyModule' }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(routes);

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