Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6: If "Cannot match any routes" moved to other component

I have a route configuration like below:

const routes: Routes = [
  { path: '', redirectTo: '/login', pathMatch: 'full' },
  { path: 'login', component: LoginComponent },
  { path: 'dashboard', component: DashboardComponent }
];

Now, if anyone wants to access xyz url like http://localhost:4200/xyz then I am getting this error

Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'xyz'

But I want to redirect to the login page in the above case.

Any idea how I can achieve that?

like image 778
Suvonkar Avatar asked Sep 18 '25 06:09

Suvonkar


1 Answers

You should be adding a wildcard route ** to catch any unexpected/unmatched/unlisted url and add the redirection to /login.

const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: 'dashboard', component: DashboardComponent },
  { path: '', redirectTo: '/login', pathMatch: 'full' },
  { path: '**', redirectTo: '/login' }
];

NOTE : The ** path in the last route is a wildcard. The router will select this route if the requested URL doesn't match any paths for routes defined earlier in the configuration. Make sure it is the last entry in list of routes!

like image 174
nircraft Avatar answered Sep 20 '25 23:09

nircraft