Angular2 Router Error: Unable to map routes: ''

I configured the Angular2 router as shown below:

import { provideRouter, RouterConfig } from '@angular/router'; import { Page2} from './page2'; const routes: RouterConfig = [ { path: 'page2', component: Page2 } ]; export const appRouterProviders = [ provideRouter(routes) ]; 

Plnkr is available here.

When I run the code, I get an error message:

 Error: Cannot match any routes: '' 

What am I missing here?

+6
source share
3 answers

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

If you want the default page to be on page2, you must give your pointer the path to redirect it as follows:

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

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

+4
source

You must define a default router for '' , for example:

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

Or using redirection:

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

See also an example from angular2 documentation

+2
source

to understand what you want to use as the default page of the app.ts page and the loaded page2 by pressing Page2 ?

Option 1: quick fix problem

Solving the current console error, you can add to your app.route.ts

 import { App} from './app'; const routes: RouterConfig = [ { path: '', component: App, useAsDefault: true } { path: 'page2', component: Page2 } ]; 

And the result will be

enter image description here

But you will see that your app.ts html will download twice at boot time! which is not a good solution!

Option 2:

As I use in my project, I recommended that you create a new home page as the default page. Then call Page2 in app.ts

Here is Plnkr http://plnkr.co/edit/vzl9lw

Will it fit your requirements!

0
source

All Articles