在Angular 2中使用路由的延迟加载模块

时间:2016-12-03 09:56:21

标签: angular angular2-routing

在我的应用程序中,我有主模块及其路由器和子模块及其路由器。

主模块(及其路由器)的路径很少,如:

/login
/sign-up
/ask
etc

子模块有很多路径:

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

我想对子模块进行延迟加载。

我现在喜欢这样:

主路由器:

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"
    }

子模块的路由器:

{   // 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
}

如果我进入主页/并在点击链接后点击导航,我的应用程序就可以完美运行。 但是如果我重新加载页面例如/ countries / search它会将我移到国家/地区页面并提供例外:“无法匹配任何路线:'搜索'”

1 个答案:

答案 0 :(得分:1)

您缺少pathMatch:full并检查您如何使用RouterModule.forChild(路由)或forRoot ..以获得更好的参考,请参阅此文档:

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);