m13r
m13r

Reputation: 26

Multiple parameters in Angular 2

I am trying to set up a browser to browse through a tree. Every time a leave is selected, its children can be selected.

Since I want to make generic, I only want to specify one route.

Unfortunatly, that does not really work... This works

RouterModule.forRoot( [
{ path: '', redirectTo: '/browser', pathMatch: 'full' },
{
    path: 'browser', children: [
    {
        path: '',
        component: BrowserComponent
    },
    {
        path: '**',
        component: BrowserComponent
    }
]
},

] )

But then I am not able to read the params. This prints an emtpy object

this.route.params.forEach((params: Params) => {
   console.log(params);
});

I think it should be something like this:

{ path: '**/:id', component: BrowserComponent }

But that does also not work..:/ Can somebody tell me what I'm doing wrong? Thanks in advance.

PS: In rails I would do it like this:

get 'browser/*id',

Upvotes: 0

Views: 331

Answers (1)

eko
eko

Reputation: 40647

Here's a plunker: http://plnkr.co/edit/kWSOa8i6095e0a5pBlgq?p=preview

In order to get the params change the routeconfig like this:

RouterModule.forRoot( [
{ path: '', redirectTo: '/browser', pathMatch: 'full' },
{
    path: 'browser', children: [
    {
        path: ':id',
        component: BrowserComponent
    },
    {
        path: '**',
        component: AnotherComponent
    }
]
},

This way, when the user goes to the url browser/1, you can see 1 in the params. I also suggest you to change the component of the wildcard route (**) because I assume you are going to use a parameter inside your BrowserComponent and if your user doesn't provide a parameter it should go to an error page.

Upvotes: 1

Related Questions