Parsa
Parsa

Reputation: 179

How handle multiple completely dynamic routes in angular?

I have multiple routes which haven't any static parameter that I can add a corresponding component for that route, so I can easily navigate. My routes config is like:

app-routing.module.ts:

const routes = {
  {path: '', component: MainPageComponent},
  {path: ':category', component: ListPageComponent},
  {path: ':productInfo', component: ProductComponent},
  {path: '404', component: PageNotFoundComponent},
  {path: '**', redirectTo: '404'}
};

At the beginning, I decided to use a resolver to first send the requested url to api and find out if the url is ok as being a category and if it wasn't I made another request to api to find out if it was OK as being a product. But I think it isn't efficient until I pass the info that the api sent to me, to the component, so the component wouldn't need to make another request and that was why I choose to use resolver. I also wanted to handle incorrect routes, so if those 2 requests to api were respond to incorrect, I wanted to navigate the user to 404 page. But I couldn't handle to connect the corresponding component for a route, in the resolver. Any advice or solution how to do this?

UPDATE: @Abhijeet Raj, thanks for your answer. Currently we changed the way we defien our routes and it ends up sth like this: {path: ':category/:slug', component: ProductComponent}, {path: ':category/:brand1/:brand2/:brand3/...', component: ListPageComponent} In this situation, when I have: '':category/brand1" it would go to the ProductComponent, instead of ListPageComponent, how I can resolve this issue?

But when I have sth like: ':category/:brand1/:brand2', because of having more than two param in url, I can use a urlMatcher.

Upvotes: 0

Views: 613

Answers (1)

d1fficult
d1fficult

Reputation: 1083

As far as I understood your problem, :category and :productInfo are no different here actually, both will open same component. If you pass any dynamic category or product info in the route it will only go to the first route listed in the routes array i.e. :category. You will need to differentiate your routes in someway like :-

category/:categoryId

and

product/:productId

So both can refer to different components.

Upvotes: 2

Related Questions