網站搜尋

javascript - 如何在路由層級中的某個點「掛載」Angular 2 模組的路由


假設我有一個主路由模組定義如下:

// app-routing.module.ts
const appRoutes: Routes = [
    {
        path: 'login',
        component: LoginComponent
    },
    {
        path: 'auth',
        component: MasterPageComponent,
        canActivate: CanActivateGuard
    }
];

然後在另一個檔案中,一個 feature 路由模組:

// feature-routing.module.ts
const featureRoutes: Routes = [
    {
        path: '/feature',
        component: FeatureComponent
    }
];

我如何將功能模組中的路由「掛載」到我的主模組下,以便我像這樣訪問它:

/auth/feature

從概念上來說,我正在尋找類似這樣的東西:

RouterModule.forChildAtMountPoint(featureRoutes, '/auth');

我知道這可以透過延遲加載來實現,但我希望這個模組被即時加載。

答案#1

這非常直接,儘管據我所知仍然尚未有文件記載。

雖然路由定義的 loadChildren 屬性通常與延遲加載相關,但它也可以被賦值為返回一個即時加載模組的函數:

// app-routing.module.ts
const appRoutes: Routes = [
    {
        path: 'login',
        component: LoginComponent
    },
    {
        path: 'auth',
        component: MasterPageComponent,
        canActivate: [CanActivateGuard],
        children: [
            {
                path: 'feature',
                loadChildren: () => FeatureModule
            }
        ]
    }
];

// feature-routing.module.ts
const featureRoutes: Routes = [
    {
        path: ''
        component: FeatureComponent
    }
];