4
votes

In angular2 how do you navigate to another route that requires an id?

I'm using this router version: "@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 }]); 

Basically I want to know how to navigate to a url with an id from the component and in a view.

Current attempt in the view:

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

Current attempt in the component:

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

Both attempts above didnt work and I got the following error:

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

Its strange because I set my route link this in my app.component:

@Routes([
{ path: '/blog/:slug', component: BlogArticle, as: 'BlogArticle' }
])
1
Try removing as: 'BlogArticle' from Route definition, it might be wrong syntax with RC1 router.Sasxa
Okay I will try tonightAngularM

1 Answers

15
votes

Having this route:

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

You can navigate to your blog from the view with the following:

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

Or you can navigate to it from your component:

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


Now that being said, you have to decide if blogId is an optional segment of your blog route or it is in fact required. If it is required then the code above is the way to go but if it is optional and may or may not be always present then I suggest to change your route to the following:

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

And then if you want to navigate to your blog with a blogId then you can do so like this:

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