【问题标题】:Angular 2 route with url parameter conflicts with other routes带有url参数的Angular 2路由与其他路由冲突
【发布时间】:2017-03-22 13:58:11
【问题描述】:

我的子模块路线如下,

{
  path: '',
  children: [
    { path: '', component: TripManagerComponent },
    { path: ':id', component: TripDetailComponent },
    { path: 'new', component: TripNewComponent }
  ]
}

我正在如下导航到这些路线,

navigateToTrip(index: number) {
  this.router.navigate([index], { relativeTo: this.route });
}

navigateToNewTrip() {
  this.router.navigate(['new'], { relativeTo: this.route });
}

但是 Angular 将 new 路由检测为 :id 并将我导航到 TripDetailComponent。

这里的问题是 Angular 检测到“新”字符串作为 :id 路由的 url 参数。

我可以为:id 添加一个前缀,即view/:id 并使其工作。但是,我需要保持 url 模式不变。有没有办法做到这一点?

我预期的 url 模式是,

/trips        --> show all trips
/trips/2334   --> show details of trip 2334
/trips/new    --> show a form to create a new trip

【问题讨论】:

    标签: angular routing


    【解决方案1】:

    目前您的:id 路由也与new 匹配,并且路由器不会进一步寻找其他匹配的路由。

    顺序是相关的。将new 路由移到:id 路由之前,然后new 路由匹配到:id 路由之前。

    {
      path: '',
      children: [
        { path: '', component: TripManagerComponent },
        { path: 'new', component: TripNewComponent }
        { path: ':id', component: TripDetailComponent },
      ]
    }
    

    【讨论】:

    • 感谢君特。有用。没想到顺序很重要。
    • 路线顺序总是让我着迷:|感谢您澄清这一点。
    • 我们如何管理完整的动态类型的 URL,没有任何部分。
    【解决方案2】:

    您不能映射具有与参数完全相同的段的两条路径(:id 匹配 new 路径)。

    但是,您可以使用以下配置手动映射正确的操作。

    {
      path: '',
      children: [
        { path: '', component: TripManagerComponent },
        { path: ':id', component: TripDetailComponent },
      ]
    }
    

    进入组件TripDetailComponent,如果参数等于new就可以触发创建过程。

    this.route.params.subscribe(
            params => {  
                    let id = params['id'];
                    if (id === "new") {
                        // Create a new element
                    } else if(p.match(/\d+/)){
                        // Display the details
                    } else {
                        // Handle when id is not a number
                    }
            },
            // Handle error
            err => this.logger.error(err),
            //Complete
            () => {}
        );
    

    此answer 与此相关。

    【讨论】:

    • 谢谢尼古拉斯。这比 Günter 的解决方案稍微复杂一些。但是我相信我可能会遇到需要在应用增长时使用这种方法来加载组件的情况。
    猜你喜欢
    • 1970-01-01
    • 2018-10-01
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多