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

落花浮王杯 提交于 2019-12-19 21:54:15

问题


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 ?


回答1:


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)



来源:https://stackoverflow.com/questions/48807518/how-to-handle-angular-5-recursive-unknown-exact-number-router-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!