Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle angular 5 recursive unknown exact number router parameters?

Is there a way to handle recursively unknown exact number of router parameters?

For example:

We have products categories, which can have subcategories, subcategories can have it's own subcategories and so on. There are a few main conditions:

  • if a such category has no subcategories we redirect to /categories/{id}/items that will open items list component.
  • if category has subcategory it should be redirected to next nested tree level /categories/{id}/{id}/.../{id} which should open the last categoryId subcategories list component.
  • after getting to the last category which doesn't has subcategories items list component will be shown /categories/{id}/{id}/.../{id}/items.

The solutions to check and redirect is to have router resolver. But how track those urls in routing module ?

From my perspective the routes should look something like this:

{
  path: '/categories/:id',
  component: SubcategoriesListComponent
},
{
  path: '/categories/:id/**/:id',
  component: SubcategoriesListComponent,
},
{
  path: '/categories/:id/**/:id/items',
  component: CategoryItemsListComponent
}

Is it possible implement it in a such way ?

like image 923
Vlad S. Avatar asked Feb 15 '18 12:02

Vlad S.


People also ask

How are parameters identified in the route configuration in Angular?

The first way is through the route snapshot. The route snapshot provides the initial value of the route parameter map (called the paramMap ). You can access the parameters directly without subscribing or adding observable operators. The paramMap provides methods to handle parameter access like get , getAll , and has .


1 Answers

Possible solution with componentless routes: in routes config

{
    path: 'categories/:id', children: [
    {path: '**', component: SubcategoriesListComponent}
]
}

in component file:

export class SubcategoriesListComponent {

  constructor(aroute: ActivatedRoute) {
    aroute.url.subscribe((data) => {
      console.log('params ', data); //contains all the segments so put logic here of determining what to do according to nesting depth
    });

  }

}

Here is the output example (i tested on my project ErrorComponent so don't be confused)

like image 158
Alexander Poshtaruk Avatar answered Oct 23 '22 02:10

Alexander Poshtaruk