需要从 Angular 7 路由器中的路由获取参数
Need to get the params from route in Angular 7 Router
我的路由器参数有问题。
{
path: 'profile',
component: ProfileComponent,
canActivate:[AuthGuard],
children: [
{
path: 'section/:id/:idarticle',
component: WriteArticleComponent,
},
]
}
一切正常。我的页面正常打开。
在这种情况下,我对这个组件形成了link
<a [routerLink]="['/profile/section', item.idSection, item.id]">
在浏览器中 url 我有这个
http://localhost:59955/profile/section/7002/5005
但是在这个页面中我需要从路由中获取参数。而我只能得到第一个
this.idSection = this.router.snapshot.params.id;
this.idArticle = this.router.params['id-article'];
第二个永远是未定义的
我试图通过这种方式形成我的url
<a [routerLink]="['/profile/section/']" [queryParams]="{id:
item.idSection, article: item.id}">
我在浏览器中有这个
http://localhost:59955/profile/section?id=7002?idarticle=5005
而且这个路由器不工作。 Link 不会重定向到那里。如果我尝试在浏览器中强制执行。它将我重定向到
http://localhost:59955/profile/section
如何使用路由器和 link 组织我的工作,在那里我可以轻松获取所有参数。
您通过快照检索第一个参数
this.idSection = this.router.snapshot.params.id;
第二个直接通过参数
this.idArticle = this.router.params['id-article'];
后者不是 return 给定参数,而是 Observable 包含所述参数。另一方面,当调用 router.snapshot
时,会创建一个包含当时参数值的快照。
因此,您也可以使用快照(如果您知道您的参数不会更改),或者您应该对两个参数都使用可观察对象并对可能发生的更改做出反应。
您可以使用第一种方法获取参数,例如
this.router.params.subscribe(data=>{
this.idArticle=data['idarticle'];
this.idSection =data['id'];
});
如果是第二种方法,您需要将 path: 'section/:id/:idarticle',
更改为 path: 'section',
,然后获取
之类的查询参数
this.router.queryParams.subscribe(data=>{
this.idArticle=data['idarticle'];
this.idSection =data['id'];
});
我的路由器参数有问题。
{
path: 'profile',
component: ProfileComponent,
canActivate:[AuthGuard],
children: [
{
path: 'section/:id/:idarticle',
component: WriteArticleComponent,
},
]
}
一切正常。我的页面正常打开。
在这种情况下,我对这个组件形成了link
<a [routerLink]="['/profile/section', item.idSection, item.id]">
在浏览器中 url 我有这个
http://localhost:59955/profile/section/7002/5005
但是在这个页面中我需要从路由中获取参数。而我只能得到第一个
this.idSection = this.router.snapshot.params.id;
this.idArticle = this.router.params['id-article'];
第二个永远是未定义的
我试图通过这种方式形成我的url
<a [routerLink]="['/profile/section/']" [queryParams]="{id:
item.idSection, article: item.id}">
我在浏览器中有这个
http://localhost:59955/profile/section?id=7002?idarticle=5005
而且这个路由器不工作。 Link 不会重定向到那里。如果我尝试在浏览器中强制执行。它将我重定向到
http://localhost:59955/profile/section
如何使用路由器和 link 组织我的工作,在那里我可以轻松获取所有参数。
您通过快照检索第一个参数
this.idSection = this.router.snapshot.params.id;
第二个直接通过参数
this.idArticle = this.router.params['id-article'];
后者不是 return 给定参数,而是 Observable 包含所述参数。另一方面,当调用 router.snapshot
时,会创建一个包含当时参数值的快照。
因此,您也可以使用快照(如果您知道您的参数不会更改),或者您应该对两个参数都使用可观察对象并对可能发生的更改做出反应。
您可以使用第一种方法获取参数,例如
this.router.params.subscribe(data=>{
this.idArticle=data['idarticle'];
this.idSection =data['id'];
});
如果是第二种方法,您需要将 path: 'section/:id/:idarticle',
更改为 path: 'section',
,然后获取
this.router.queryParams.subscribe(data=>{
this.idArticle=data['idarticle'];
this.idSection =data['id'];
});