【问题标题】:How to load child route by default in angular 2如何在角度2中默认加载子路由
【发布时间】:2017-06-02 16:21:51
【问题描述】:

在应用程序开始时,我想加载子路由。

现在 URLcome,但相应的组件没有加载到该部分,但是当再次点击它的实际 URL 时。

就像路由配置是

  const appRoutes: Routes = [
        { path: 'a', component: AComponent,
         children:[
                   { path:'x',component:AXcomponent }
                   ]
        },
        { path: 'b', component: bComponent, }
]

现在我想加载路径 a/x 我将如何在页面开头加载?

【问题讨论】:

  • 可能我没有理解正确,但是你应该可以使用{ path: '', redirectTo: '/a/b', pathMatch: 'full' }, 让你的空路径''重定向到'/a/b'然后加载对应的组件。跨度>
  • 设置了不工作的 url 但第一次未加载组件但点击直接 url 然后加载

标签: angular routes


【解决方案1】:

自动添加空路径路由作为重定向

const appRoutes: Routes = [
    {
        path:'',
        redirectTo: 'a',
        pathMatch: 'full' 
    },
    {
        path: 'a',
        component: AComponent,
        children:[
            {
                path:'',
                redirectTo: 'x',
                pathMatch: 'full' 
            },
            {
                path:'x',
                component: AXcomponent 
            }
        ]
    },
    { 
        path: 'b',
        component: bComponent
    }
];

【讨论】:

  • 在 url 的变化就像 url set /a/b 但是没有加载相应的组件
  • 它的工作,感谢我的代码中有一些错误现在它工作了。:)
  • 太好了...很高兴我能帮上忙!
  • 如果子路由包含出口会怎样?
  • @LuisRuizFigueroa 你对出口场景有什么想法吗?
【解决方案2】:

如果您的子路线包含出口,则接受的答案无效。

例如,我按 ID 显示“订单”,并为摘要和其他面板使用命名的出口“详细信息”。

/orders/5000001/(detail:summary)
/orders/5000001/(detail:edit)

因为这些 URL 太丑了,我还希望以下两个重定向:

/orders/5000001           =>    /orders/5000001/(detail:summary)
/orders/5000001/summary   =>    /orders/5000001/(detail:summary)

所以我在孩子中尝试了无组件重定向:

{ path: '', pathMatch: 'full', redirectTo: '(detail:summary)' }

这失败了,因为'redirectTo' 需要是绝对的(我确信这有一个复杂的技术原因)。所以我尝试了这个:

{ path: '', pathMatch: 'full', redirectTo: '/order/:id/(detail:summary)' }

这失败了,因为:id 不是子上下文中的命名变量。

所以最后我想通了:

 children: [

     { path: ':id', pathMatch: 'full', redirectTo: '/orders/:id/(detail:summary)' },
     { path: ':id/summary', pathMatch: 'full', redirectTo: '/orders/:id/(detail:summary)' },
     {
         // this goes in the main router outlet
         path: ':id', component: OrderFulldetailsComponent,

         children: [

             { path: 'summary', component: OrderSummaryComponent, outlet: 'detail' },
             { path: 'edit', component: OrderEditComponent, outlet: 'detail' }
         ]
     }
 ]

请注意,在path: ':id' 上执行pathMatch: 'full' 很重要,否则当您点击/:id/(detail:summary) 时它会匹配,但无处可去。

【讨论】:

    猜你喜欢
    • 2018-07-30
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 2018-04-22
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多