【问题标题】:Angular 2 routing, adding child routes causes route not to workAngular 2路由,添加子路由会导致路由不起作用
【发布时间】:2016-09-23 11:35:38
【问题描述】:

在使用最新版本玩 angular 2 路由时,我注意到添加子路由会导致下面的 /admin 路由不起作用

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AdminComponent } from './admin.component';
import {AdminChildComponent} from './admin-child.component';

import {productRoutes} from "../product/product.routes";

export const adminRoutes : Routes =[
  {
    path: 'admin', component: AdminComponent,
    children:[
      {path:"/child", component:AdminChildComponent}
    ]
  }
];

export const adminRouting: ModuleWithProviders = RouterModule.forChild(adminRoutes);

一旦我在下面删除,应用程序就可以正常工作,一旦我添加它,我就会收到控制台错误

异常:未捕获(承诺):错误:无法匹配任何路由: '管理员'

   children:[
      {path:"/child", component:AdminChildComponent}
    ]

可能需要帮助来了解为什么会出现此错误。完全混乱。

【问题讨论】:

    标签: angular angular2-routing


    【解决方案1】:

    那是因为:

    在这里可以清楚地看到 AdminComponent 有孩子。这意味着 AdminComponent 将在模板中的某处具有 router-outlet

    现在的问题是,每当使用 router-outlet 时,都需要 view。在您的路由情况下,它没有任何正确/主要的子路由。所以需要如下图设置,

    export const adminRoutes : Routes =[
      {
        path: 'admin', component: AdminComponent,
        children:[
    
          { path: '', redirectTo: 'child', pathMatch: 'full'}, //<----- here
    
          {path:"child", component:AdminChildComponent}
        ]
      }
    ];
    

    注意:已将 /child 更改为 child。为什么?因为 angular2 路由器本身在父路由和子路由之间添加了/。所以这里你不需要/

    【讨论】:

    • 我不明白为什么需要这样的配置。尽管如此,添加您建议的 {path: '', ... } 会产生异常 EXCEPTION: Uncaught (in promise): Error: Cannot match any routes: 'child'
    • 我已经在回答中解释了为什么需要这样的路线。
    • 我理解了您的解释,也考虑了您的回答,并与其他带有子路线的路线进行了比较。是的,您似乎总是需要一个空路由来重定向或路由到组件。我的问题是“/child”而不仅仅是“child”
    • 我知道这一点。但我仍然建议您使用/child,但它应该只是child
    猜你喜欢
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    • 2017-12-12
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多