Home > Net >  Angular Router with keywords in url
Angular Router with keywords in url

Time:11-08

I am trying to set up path for the following combination of urls

  • /red-cars-for-sale-fl
  • /used-cars-for-sale-ca
  • /new-cars-for-sale-ga
  • /fast-cars-for-sale-fl and so on.

All these urls should match one component CarSaleComponent. Similarly, boats-for-sale set of urls should instantiate BoatSaleComponent and so on

 { path: ':param1', component: CarSaleComponent }, 
 { path: ':param1', component: BoatSaleComponent }, 
 { path: 'contact', component: ContactComponent }

This does not work because /contact will also match the first path and instantiate CarSaleComponent. I am using a workaround as

 { path: 'cars/:param1', component: CarSaleComponent }, 
 { path: 'boats/:param1', component: BoatSaleComponent },
 { path: 'contact', component: ContactComponent }

is it possible to match the path based on "cars-for-sale" or "boats-for-sale" sub-strings ?

CodePudding user response:

You have to align the routes path like that the last one will match any cases so the code will be like this

{ path: 'contact', component: ContactComponent },
{ path: ':param1', component: CarSaleComponent }

This way if the contact is called it will work if no routes matches the given it will go to params one

CodePudding user response:

There can be two ways of doing this.

  1. You can pass the params in the URL to tell the sale for boat/car. Based on the input you show/hide the CarSaleComponent/BoatSaleComponent. The bad side is if you add more items for sale you might need to add a config which enables/disables the list of component.

  2. You can create routes for every item item-for-sale and pass the necessary information in the query.

 { path: 'car-for-sale', component: CarSaleComponent }, 
 { path: 'boat-for-sale', component: BoatSaleComponent }, 
 { path: 'contact', component: ContactComponent }

You can also create a sale module and lazy load it when the user try to access this specific information. You can also create child routes for different items under it and route them accordingly.

Also, the routes match is based on the how they are define in the routing from top to bottom. So, always put them in the way you match root / in the end.

  • Related