加载同一模块的多个路径 - 延迟加载

Dha*_*ran 9 angular angular-router

我在一个模块中有多个组件。我想根据路由路径显示组件。对于http://localhost:4200/account我想显示帐户组件。对于http://localhost:4200/setting我想显示设置组件 ..etc

app.routing.module.ts

{
    path: 'account',
    loadChildren: './modules/settings/settings.module#SettingsModule',
},
{
    path: 'settings',
    loadChildren:'./modules/settings/settings.module#SettingsModule', 
},
Run Code Online (Sandbox Code Playgroud)

settings.routing.module.ts

export const routes: Routes = [
    {
        path: 'account',
        component: accountComponent
    },
    {
        path: 'account/edit',
        component: accountEditComponent
    },
    {
        path: 'settings',
        component: settingsComponent
    },
    {
        path: 'settings/edit',
        component: settingsEditComponent
    }
];
Run Code Online (Sandbox Code Playgroud)

我在 settings.routing.module.ts 中做了哪些更改以显示这些组件。

ben*_*oam 13

如果你真的想这样做,你可以使用UrlMatcher来找到正确的组件。

旁注:我不建议你这样做。而是使用我的另一个答案。我认为这是一个更好的方法。但是——当然这是你的决定。

简单演示

app.routing.module.ts(未更改)

{
    path: 'settings/account',
    loadChildren: './modules/settings/settings.module#SettingsModule',
},
{
    path: 'settings',
    loadChildren:'./modules/settings/settings.module#SettingsModule', 
}
Run Code Online (Sandbox Code Playgroud)

settings.routing.module.ts

export function isAccount(url: UrlSegment[], group: UrlSegmentGroup) {
  return group.segments.length === 1 && group.segments[0].path.endsWith('account') ? ({consumed: url}) : null;
}

export function isSettings(url: UrlSegment[], group: UrlSegmentGroup) {
  return group.segments.length === 1 && group.segments[0].path.endsWith('settings') ? ({consumed: url}) : null;
}

export const routes: Routes = [
    {
        path: 'account',
        component: accountComponent,
        matcher: isAccount
    },
    {
        path: 'account/edit',
        component: accountEditComponent
    },
    {
        path: 'settings',
        component: settingsComponent,
        matcher: isSettings
    },
    {
        path: 'settings/edit',
        component: settingsEditComponent
    }
];
Run Code Online (Sandbox Code Playgroud)

结果正是您要寻找的:

http://localhost:4200/settings将显示设置组件。

http://localhost:4200/account将显示帐户组件。