Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

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' }
])
like image 258
AngularM Avatar asked Dec 05 '22 17:12

AngularM


1 Answers

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 }]"
like image 118
Morteza Manavi Avatar answered Dec 09 '22 13:12

Morteza Manavi