首页 > 解决方案 > Angular 6延迟加载路由问题

问题描述

我想在你的应用程序中使用延迟加载。A 有 2 个模块:登录和汽车。延迟加载工作正常,但 route /add-car 不工作。为什么?找不到路径 /add-car 并重定向到 PageNotFoundComponent。

app.routing.module.ts

const appRoutes: Routes = [
    {
        path: '',
        pathMatch: 'full',
        redirectTo: 'login'
    },
    {
        path: 'cars',
        canLoad: [AuthCanLoadGuard],
        loadChildren: './cars/cars.module#CarsModule',
    },
    {
        path: 'user-account',
        component: UserAccountComponent,
        canActivate: [AuthGuardsService]
    },
    {
        path: '**',
        component: PageNotFoundComponent
    }
];

@NgModule({
    imports: [RouterModule.forRoot(appRoutes, {enableTracing: true})],
    exports: [RouterModule]
  })

car.routing.module.ts

const carsRoutes: Routes = [
    {
        path: '',
        component: CarsComponent,
        children: [
            {
                path: '',
                component: CarsListComponent,
                resolve: { cars : CarsListResolve } // przeniesione z app.routing.module.ts
            },
            {
                path: ':id',
                component: CarsDetailsComponent,
                canDeactivate: [FormCanDeactivateGuard],
                resolve: { car: CarResolve }
            }
        ]
    },
    {
        path: '/add-car',
        component: AddCarComponent,

    }
];

@NgModule({
    imports: [RouterModule.forChild(carsRoutes)],
    exports: [RouterModule]
  })

标签: angulartypescript

解决方案


路径不能以斜杠开头。调整/add-caradd-car

{
        path: 'add-car',
        component: AddCarComponent,

    }

而且,如上面的答案所述,您还需要/cars上下文。作为add-car一个孩子,它仅在 下可用/cars,因此您使用的路径在浏览器中是/cars/add-cars


推荐阅读