【问题标题】:Angular 2 router pathsAngular 2 路由器路径
【发布时间】:2016-11-28 18:03:07
【问题描述】:

我有 2 个关于 Angular 2 路由器路径的问题,我花了一些时间在谷歌上搜索它,但没有运气,无论如何我有以下路由设置:

{ path: 'contract', component: ContractInsertUpdateComponent, children: [
         { path: '' },
         { path: ':id', component: ContractInsertUpdateComponent, children:[
                  { path: 'buyers', component : ContractTabBuyerComponent },
                  { path: 'seller', component : ContractTabSellerComponent }
        ]}                
]}

首先,让我解释一下我想在这里实现什么,我想使用相同的组件来插入/更新合同。我还有更多的子路线,完整的 url 应该看起来像

localhost:4200/contract/2/buyers

  1. 我首先好奇的是合同的默认路径

    { 路径:'' }

如果路线类似于

localhost:4200/合约

它应该加载它执行 atm 的 ContractInsertUpdateComponent,我的问题是:这是正确的方法吗?如果可能的话,我也想避免使用空组件作为默认路由。

  1. 此路由设置的其余部分当前不起作用,例如,如果我键入类似
  2. 的内容

localhost:4200/contract/2

我收到错误:无法匹配任何路由。 URL 段:'contract/2'

据我了解,它应该加载 ContractInsertUpdateComonent 我错了吗?

我不知道还能去哪里寻求帮助,我需要有人指引我正确的方向...提前感谢您的帮助!

【问题讨论】:

    标签: angular angular2-routing


    【解决方案1】:

    `/contract/2 匹配这条路由

    { path: '' },
    

    因为/contract/2'' 开头(实际上每条路线都是如此) 然后搜索这条路由的子路由但是因为没有子路由而失败。

    { path: '', pathMatch: 'full' },
    

    应该修复它,因为这样路由器不会搜索以'' 开头的路由,而只会搜索 ''

    的路由

    更新

    { path: 'contract', component: ContractInsertUpdateComponent, children: [ 
        { path: '', pathMatch:'full', /* I guess you want some `component: ...` or `redirectTo: ...` here }, 
        { path: ':id', children:[ 
            { path: '', pathMatch:'full' }, 
            { path: 'seller', component : ContractTabSellerComponent } 
        ]} 
     ]}
    

    【讨论】:

    • 好吧,谢谢,使用你的逻辑,我设法让它工作(有点) - 我在两条子路线上添加了{ path: '', pathMatch: 'full' },所以现在看起来像这样:{ path: 'contract', component: ContractInsertUpdateComponent, children: [ { path: '', pathMatch:'full' }, { path: ':id', children:[ { path: '', pathMatch:'full' }, { path: 'seller', component : ContractTabSellerComponent } ]} ]} 现在我有一个问题,因为在我的 ContractInsertUpdateComponent 参数(id)值是 NaN。有什么想法吗?
    • id 仅传递给 ContractTabSellerComponent。您可以在那里使用它,也可以将其传递给父级。还有一种方法可以通过父路由的参数找到子路由,但这似乎有点脆弱。
    • 另见stackoverflow.com/questions/38956129/…了解后一种方法
    • 嗯,是的,我认为你是对的...这确实有点奇怪...我想我必须重新配置它...问题是我不想加载组件或在空路径上重定向,我只想在两条路线上加载 InsertUpdateComponent - 合同或合同/2 应该都加载相同的组件(InsertUpdateComponent)和编辑路线(合同/2)应该有子路线 - 买方和卖方......无论如何, tyvm 为你的帮助伙伴,我真的很感激。
    猜你喜欢
    • 1970-01-01
    • 2020-08-30
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多