Search code examples
javascriptangularangular-routing

Angular Router error redirecting to path with dynamic parameter


I want to redirect user to a path with a unique UUID when they hit root (localhost:4200).

But I get this error

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'document/4fdb309b-df59-4da8-a32d-5265f7925bba'

Error: Cannot match any routes. URL Segment: 'document/4fdb309b-df59-4da8-a32d-5265f7925bba'

Below is my router module code segment

import { v4 as uuidv4} from 'uuid'

const routes : Routes = [
  {path : '', redirectTo : '/document/'+uuidv4(), pathMatch: 'full'},
  {path : 'documents/:id', component: DocumentComponent}
]

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {
}

Not sure whats wrong!


Solution

  • Most probably it's due to route ordering. Try to rearrange the routes

    const routes : Routes = [
      {path : 'documents/:id', component: DocumentComponent},
      {path : '', redirectTo : '/document/'+uuidv4(), pathMatch: 'full'}
    ]
    

    Note that Angular Router uses first-match wins strategy and the ordering of the routes in the array does matter.