简体   繁体   English

将 ID 添加为 URL 中的参数时,Angular Routing 不起作用

[英]Angular Routing not working when adding ID as a parameter in URL

new to Angular here.这里是 Angular 的新手。 I have the following in my app.module.ts我的 app.module.ts 中有以下内容

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

The following is redirecting correctly to PostprofileComponent .以下是正确重定向到PostprofileComponent

http://localhost:4200/posts/2 http://localhost:4200/posts/2

However this link does not... it redirects to PostsComponent .但是,此链接不会...它重定向到PostsComponent

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

Shouldn't they behave the same?他们的行为不应该一样吗? What am i doing wrong?我究竟做错了什么?

In your RouterModule :在您的RouterModule

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

Usage example using query params : (More info here )使用查询参数的用法示例:(此处有更多信息)

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

URL: http://localhost:4200/posts/details?id=2 return to => PostprofileComponent URL: http://localhost:4200/posts/details?id=2返回=> PostprofileComponent


Usage example using route params :使用路由参数的用法示例:

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

URL: http://localhost:4200/posts/details/2 return to => PostprofileComponent URL: http://localhost:4200/posts/details/2返回=> PostprofileComponent


then http://localhost:4200/posts return to => PostsComponent然后http://localhost:4200/posts返回到 => PostsComponent

The second option is using url query parameters while the first option is using angular routing parameters.第二个选项是使用 url 查询参数,而第一个选项是使用角度路由参数。

ie using this:即使用这个:

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

would result in your first route http://localhost:4200/posts/2将导致您的第一条路线http://localhost:4200/posts/2

and then this:然后这个:

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

would result in second route http://localhost:4200/posts?id=2将导致第二条路线http://localhost:4200/posts?id=2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM