【问题标题】:Angular Routing not working when adding ID as a parameter in URL在 URL 中添加 ID 作为参数时,角度路由不起作用
【发布时间】:2020-02-17 19:47:58
【问题描述】:

这里是 Angular 的新手。我的 app.module.ts 中有以下内容

RouterModule.forRoot()
{
...
      { 
        path : "posts/:id",
        component: PostprofileComponent 
      },
      { 
        path : "posts",
        component: PostsComponent 
      },
...
}

以下内容正确重定向到PostprofileComponent

http://localhost:4200/posts/2

但是这个链接没有...它重定向到 PostsComponent

http://localhost:4200/posts?id=2

他们的行为不应该一样吗?我做错了什么?

【问题讨论】:

  • 你做错了什么?您期望它们的行为相同。它们不一样。
  • Angular 中的查询参数允许跨应用程序中的任何路由传递可选参数。查询参数不同于常规路由参数,后者仅在一个路由上可用,不是可选的(例如:/posts/:id)。

标签: angular routing


【解决方案1】:

在你的RouterModule

RouterModule.forRoot()
{
...
    {
        path : "posts/details/:id",
        component: PostprofileComponent
    },
    {
        path : "posts/details",
        component: PostprofileComponent
    },
    {
        path : "posts",
        component: PostsComponent
    },
...
}

使用查询参数的使用示例:(更多信息here

this.router.navigate(['/posts/details'], { queryParams: { id: '2' } });

网址:http://localhost:4200/posts/details?id=2 返回=> PostprofileComponent


使用路由参数的使用示例:

this.router.navigate(['/posts/details', '2']);

网址:http://localhost:4200/posts/details/2返回=>PostprofileComponent


然后http://localhost:4200/posts 返回=> PostsComponent

【讨论】:

  • 感谢莱安德罗的澄清!我现在看到我有点误解了这个概念。现在它更有意义了......
  • 如果此回复解决了您的问题,请关闭帖子 =)
【解决方案2】:

第二个选项是使用 url 查询参数,而第一个选项是使用角度路由参数。

即使用这个:

   this.router.navigate(['/posts', '2']);

将导致您的第一条路线http://localhost:4200/posts/2

然后是这个:

this.router.navigate(['/posts'], { queryParams: { id: '2' } });

将导致第二条路线http://localhost:4200/posts?id=2

【讨论】:

  • 但是在RouterModule,你必须区分PostprofileComponentPostsComponent这两个组件
  • 对...所以 localhost:4200/posts/id=2 路由将转到 PostsComponent 页面,因为它在技术上使用可选参数路由到 /posts 而他希望它转到 posts/2 ,而这是完全不同的路线。
猜你喜欢
  • 2018-01-12
  • 2017-06-22
  • 2016-05-06
  • 2019-07-20
  • 2018-05-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多