Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Router Error: Cannot match any routes: ''

I have configured Angular2 Router as below:

import { provideRouter, RouterConfig } from '@angular/router';
import { Page2} from './page2';

const routes: RouterConfig = [
  { path: 'page2', component: Page2 }
];

export const appRouterProviders = [
  provideRouter(routes)
];

Plnkr available here

On Running the code I get the error:

Error: Cannot match any routes: ''

What am I missing here ?

like image 692
runtimeZero Avatar asked Jul 13 '16 14:07

runtimeZero


2 Answers

You need to specify a route for the case where the user is at the index page of your app, that route is the path '' and it should look like this: { path: '', component: MyComponent }

If you want your default page to be page2 you must tell your index path to redirect to it like this:

{ path: 'page2', component: Page2 },
{ path: '', redirectTo: '/page2', pathMatch: 'full' }

The order here is important, the most specific route should come first.

like image 71
Diego Fontenelle Avatar answered Nov 15 '22 09:11

Diego Fontenelle


You should define default router for '' like:

const routes: RouterConfig = [
  { path: '', component: Home }, 
  { path: 'page2', component: Page2 }
];

Or by using redirect:

const routes: RouterConfig = [
  { path: '', redirectTo: '/page2', pathMatch: 'full' }, 
  { path: 'page2', component: Page2 }
];

See also the example from angular2 documentation

  • https://angular.io/docs/ts/latest/guide/router.html#!#redirect
like image 32
yurzui Avatar answered Nov 15 '22 09:11

yurzui