我有以下路由:


export const routes: Routes = [
    {
        // allowed for user with token
        path: 'admin', component: AdminMainComponent,
        canActivate: [authGuard],
        children: [
            {
                path: 'products',
                component: AdminProductListComponent,
                children: [
                    {path: 'create', component: AdminCreateProductComponent},
                ]
            },
            {
                path: 'categories',
                component: CategoryListComponent,
                children: [
                    {path: 'create', component: CreateCategoryComponent}
                ]
            },
        ]
    },

   ... 
];

当我访问/admin/products/create时,我看到了AdminProductListComponent的内容.同样的问题是分类.怎么了?

推荐答案

子管线在其父构件中渲染. 这意味着父组件必须包含<router-outlet/>,才能呈现其子组件.

如果您的路由配置高于AdminProductListComponent,则其子 node (AdminCreateProductComponent)必须包含<router-outlet/>.

如果AdminCreateProductComponent不打算在AdminProductListComponent中呈现,则应将它们定义为通用的"products"路径下的同级:

export const routes: Routes = [
  {
    path: 'admin', 
    component: AdminMainComponent,
    canActivate: [authGuard],
    children: [
      {
        path: 'products',
        children: [
          { path: '',       component: AdminProductListComponent   },
          { path: 'create', component: AdminCreateProductComponent },
        ]
      },
      {
        path: 'categories',
        children: [
          { path: '',       component: CategoryListComponent   },
          { path: 'create', component: CreateCategoryComponent },
        ]
      },
    ]
  },
];

请注意,"products"和"categories"路径没有指定component,因此父组件将是AdminMainComponent.


你也可以删除中间路径,并将所有路由声明为"admin"的直接子级:

export const routes: Routes = [
  {
    path: 'admin', 
    component: AdminMainComponent,
    canActivate: [authGuard],
    children: [
      { path: 'products',          component: AdminProductListComponent   },
      { path: 'products/create',   component: AdminCreateProductComponent },
      { path: 'categories',        component: CategoryListComponent       },
      { path: 'categories/create', component: CreateCategoryComponent     },
    ]
  },
];

Angular相关问答推荐

try 测试具有Angular material 下拉列表的组件时,在Angular 17中发现&q;错误的意外合成属性@TransitionMessages

Angular 类型的表单不能分配给分部类型

HTTP POST响应失败Angular 16

如何确保[共享]组件是真正的哑组件?(Angular )

Angular 16模块中未使用的组件是否从Bundle 包中删除(树摇动)?

使用 Electron 打包器打包 Electron Angular 应用程序时无法加载资源

Angular 路由中的模块构建失败

PrimeNG 避免在同一位置使用不同键的 cogo toast 重叠

正确理解 angular14 中的注入 - 必须从注入上下文中调用注入()

在更改检测之前调用创建的间谍

无法读取 angular2 中未定义(…)的属性 push

Angular2 路由 VS ui-router-ng2 VS ngrx 路由

Angular2 CLI 错误@angular/compiler-cli包未正确安装

如何添加/设置环境 Angular 6 angular.json 文件

*ngIf 带有多个异步管道变量

Angular 2中不同页面的多种布局

formGroup 需要一个 FormGroup 实例

升级到 angular-6.x 会给出Uncaught ReferenceError: global is not defined

Angular2/4 中的ng-reflect-*属性有什么作用?

Angular2:CoreModule 与 SharedModule