danda
danda

Reputation: 583

Defining a route with unknown number of path in the middle

I have a route named "articles", in the end of the route I get an id, but in the middle I can have one path, two paths, more or even no extra paths at all.

For example:

article/111

article/publication/222

article/publication/book/555

Is there a way to define such route without knowing the exact number of paths in the middle between the "articles" and the id? I just need in the component to extract the id, the rest of the path does not interest me.

something like this-

const appRoutes: Routes = [
  
    { path: 'articles(/:param)*/:id',
        component: ArticlesComponent
    }
];

Upvotes: 1

Views: 1057

Answers (2)

Robert Dempsey
Robert Dempsey

Reputation: 458

You can define the "middle route params" as one parameter which is a comma separated string, then split the string when parsing that URL parameter.

const appRoutes: Routes = [
  
    { 
        path: 'articles/:param/:id',
        component: ArticlesComponent
    }
];
this.route.paramMap.subscribe(params => {
 /// do something with params.get('id')
 /// do something with params.get('param')?.split(',')
})

Upvotes: 0

Gopal Mishra
Gopal Mishra

Reputation: 1945

This is not a solution but a hack.

If /article/anything/anything/:id and /article/:id routes to same component then you can have a seperate routing module for ArticleComponent like below:

const routes: Routes = [
  {
    path: '',
    component: ArticleComponent
  },
  {
    path: '**',
    component: ArticleComponent
  }
];

Since we have used the wild card route it will accept all possible routes.

and if u want to get the last path i.e. id which you can get from ActivatedRoute Object like below:

  constructor(
    private route: ActivatedRoute
  ) { 
      const paths = this.route.url.value
      const id = paths[paths.length-1].path
      console.log(id);
    }

Upvotes: 1

Related Questions