首页 文章

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

提问于
浏览
3

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

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

This is my app.component route I want to navigate to:

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

This is my other component trying to navigate to it:

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

基本上我想知道如何导航到具有组件和视图中的id的URL .

Current attempt in the view:

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

Current attempt in the component:

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

上面的两次尝试都没有工作,我得到以下错误:

Error: Uncaught (in promise): Cannot match any routes.

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

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

1 回答

  • 6

    有这条路线:

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

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

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

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

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

    既然如此,您必须决定blogId是否是您博客路线的可选部分,或者实际上是必需的 . 如果需要则上面的代码是要走的路,但如果它是可选的,可能会或可能不会总是存在,那么我建议你的路线更改为以下:

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

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

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

相关问题