首页 > 解决方案 > Angular Routing not working when adding ID as a parameter in URL

问题描述

new to Angular here. I have the following in my app.module.ts

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

The following is redirecting correctly to PostprofileComponent.

http://localhost:4200/posts/2

However this link does not... it redirects to PostsComponent.

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

Shouldn't they behave the same? What am i doing wrong?

标签: angularrouting

解决方案


在你的RouterModule

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

使用查询参数的用法示例:(更多信息在这里

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


推荐阅读