angular - 在与 parent 相同的路由器 socket 中使用子路由

标签 angular angular2-routing

我希望能够对某些路由使用相同的路由器导出。

路由设置(简化):

export const routes: Routes = [
    {
        path: 'app', component: AppComponent,
            children: [
                path: 'category/:id', component: CategoryComponent,
                children: [
                    { path: 'post/:id', component: PostComponent }
                ]
            ]
    }
];

例如我们有这个路径:

/app/category/1/post/1

闯入

/app - AppComponent
|_ /catory/1 - CategoryComponent
   |_/post/1 - PostComponent

AppComponent有一个 <router-outlet>这呈现 CategoryComponent , 但也应该呈现 PostComponent当该路由处于事件状态时。

此类问题的常见答案:

移动子路由并将它们添加到 app-route children 数组中

没有。这不是正确的方法。我们仍然需要我们的路线层次结构。 CategoryComponent可能知道哪些PostComponent没有 - 例如 Breadcrumb命名

所以我们仍然希望加载我们的 CategoryComponent。 (即使它的 View 未呈现)

使用 <router-outlet> CategoryComponent 内部

没有。 CategoryComponent不应该管它自己<router-outlet> . PostComponent应该代替 CategoryComponent 呈现, 并添加 CSS 放置它应该是非法的。

我怎样才能实现这种行为?

我需要编写自己的路由器 socket 吗?

这会在 Angular4 中解决吗?

欢迎任何提示!谢谢

最佳答案

如果我做对了,您可以尝试使用“包装器”之类的东西来解决问题。这样(我没有测试过这段代码,但它应该可以工作;阅读内联注释):

export const routes: Routes = [
    {
        path: 'app',
        component: AppComponent,
        children: [
            {
                path: 'category/:id', // app/category/:id/
                children: [
                    {
                        path: '', // app/category/:id/ => By default, empty paths serve as if they were the parent path.
                        component: CategoryComponent,
                        children: [ // These children will be inside the <router-outlet> of the CategoryComponent.
                            {
                                path: 'subcategory1', // app/category/:id/subcategory1
                                component: PostComponent,
                            },
                            {
                                path: 'subcategory2', // app/category/:id/subcategory2
                                component: PostComponent,
                            }
                        ]
                    },
                    { // The PostComponent will use AppComponent as its parent; will be loading inside the <router-outlet> of AppComponent.
                        path: 'post/:id', // app/category/:id/post/:id
                        component: PostComponent
                    }
                ]
            }
        ],
    },
];

关于angular - 在与 parent 相同的路由器 socket 中使用子路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41851898/

相关文章:

angular - 我能够在 Angular 8 的输入字段中显示从 API 获取的数据,但在控制台中出现错误

Angular http get 返回空数组

angular - 如何在 CanActivate 守卫中获取 url 段

Angular 2 : Multiple router-outlet in Child Componet

javascript - `${}` 在 Angular 中有什么用?

angular - 我在 Angular 中遇到这样的错误

angular - 在不使用::ng-deep、/deep/或 >>> 组合器的情况下设置第三方组件样式的正确方法是什么?

javascript - 如何在 Angular 2 JS 中使用管道?

angular - 创建带有可选子项的路由

Angular2 默认路由 View