【问题标题】:In angular2 how do you navigate to another route that requires an id?在 angular2 中,您如何导航到需要 id 的另一条路线?
【发布时间】:2023-03-26 18:42:01
【问题描述】:

在 angular2 中如何导航到需要 id 的另一条路线?

我正在使用这个路由器版本:"@angular/router": "2.0.0-rc.1"

这是我要导航到的 app.component 路由:

{ path: '/blog/:slug', component: BlogArticle, as: 'BlogArticle' }

这是我试图导航到它的另一个组件:

this.router.navigate(['blog', { slug: blogId }]); 

基本上我想知道如何从组件和视图中导航到带有 id 的 url。

视图中的当前尝试:

[routerLink]=" ['/blog', {slug: blogId }]"

组件中的当前尝试:

this.router.navigate(['blog', { slug: blogId }]);

上述两次尝试均无效,我收到以下错误:

错误:未捕获(承诺中):无法匹配任何路由。

这很奇怪,因为我在 app.component 中设置了路由链接:

@Routes([
{ path: '/blog/:slug', component: BlogArticle, as: 'BlogArticle' }
])

【问题讨论】:

  • 尝试从Route定义中删除as: 'BlogArticle',这可能是RC1路由器的语法错误。
  • 好的,我今晚试试

标签: angular


【解决方案1】:

有这条路线:

{ path: '/blog/:slug', component: BlogArticle }

您可以使用以下视图从视图导航到您的博客:

[routerLink]="['/blog', blogId]"

或者你可以从你的组件导航到它:

this.router.navigate(['/blog', blogId]);


话虽如此,您必须决定 blogId 是您的博客路由的可选部分还是实际上是必需的。如果需要,那么上面的代码就是要走的路,但如果它是可选的并且可能会或可能不会总是存在,那么我建议将您的路线更改为以下内容:

{ path: '/blog', component: BlogArticle }

然后,如果您想使用 blogId 导航到您的博客,那么您可以这样做:

[routerLink]="['/blog', { blogId: id }]"

【讨论】:

  • 我在 app.component 中有 2 条博客路由:@Routes([ { path: '/blog', component: BlogArticle, as: 'BlogArticle' } { path: '/blog/: slug',组件:BlogArticle,如:'BlogArticle' } ])
  • 这些路线中的任何一条都会造成问题
  • 是的,如果是这种情况,您可以在没有 ID 的情况下转到博客页面,然后使用第二种方法:删除路由 /blog/:slug 并将 ID 作为可选参数发送,就像我如何显示在我的回答中。
  • 好的,期待结果:)
  • 你如何导航到它们?
猜你喜欢
  • 1970-01-01
  • 2020-01-14
  • 2018-08-04
  • 2016-02-07
  • 2017-12-14
  • 2022-07-18
  • 1970-01-01
  • 1970-01-01
  • 2017-01-08
相关资源
最近更新 更多