angular - 需要从 Angular 7 路由器中的路由获取参数

标签 angular angular2-routing

我的路由器参数有问题。

{
  path: 'profile',
  component: ProfileComponent,
  canActivate:[AuthGuard],
  children: [
    {
      path: 'section/:id/:idarticle',
      component: WriteArticleComponent,
    },
  ]
}

一切正常。我的页面正常打开。

在这种情况下,我形成了指向该组件的链接

<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

而且这个路由器不工作。链接不会重定向到那里。如果我尝试在浏览器中强制执行。它将我重定向到

http://localhost:59955/profile/section

如何使用路由器和链接来组织我的工作,在那里我可以轻松获取所有参数。

最佳答案

您通过快照检索第一个参数

this.idSection = this.router.snapshot.params.id;

第二个直接通过参数

this.idArticle = this.router.params['id-article'];

后者不返回给定参数,而是返回包含所述参数的Observable。另一方面,当调用 router.snapshot 时,会创建一个包含当时参数值的快照。

因此,您也可以使用快照(如果您知道您的参数不会更改),或者您应该对两个参数都使用可观察对象并对可能发生的更改使用react。

关于angular - 需要从 Angular 7 路由器中的路由获取参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57488539/

相关文章:

node.js - 如何在 Electron 中使用 node_modules?

java - 无法执行目标 org.apache.maven.plugins :maven-jar-plugin:2. 6:jar

angular - TS2416 : Property 'canActivate' in type 'MyGuard' is not assignable to the same property in base type 'CanActivate'

使用 (2.0.0-rc.5) 路由的 Angular2 路由

javascript - 如何防止对象/数组突变?

Angular 2路由更改为同一组件导致重新加载

angular - *ngFor trackBy 多个属性

javascript - 如何从模型 Angular 中填充类属性?

javascript - 哪个是 Angular2/Typescript For Windows 的最佳 IDE

Angular 2新路由器routerCanReuse