I just started learning Angular2 and created a sample project in which i need to route between three pages.
I created a RouterModule in the app.module.ts as the following
@NgModule({
imports: [
BrowserModule,
HttpModule,
FormsModule,
RouterModule.forRoot([
{path:'login',component : loginComponent},
{path:'logout',component :logoutComponent},
{path:'home',component : homeComponent}
])
my app.component.ts is as the following:
@Component({
selector: 'my-app', // <my-app></my-app>
providers: [Wakanda],
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
my loginComponent.ts
@Component({
selector:'login',
template : `
<h1>Login</h1>
`
})
my logoutComponent.ts
@Component({
selector:'logout',
template : `
<h1>Login</h1>
`
})
my homeComponent.ts
@Component({
selector : 'home',
template : `
<h1>Login</h1>
`
})
my app.component.html
<header>
<nav>
<div class="nav-wrapper">
<ul class="right hide-on-med-and-down">
<li>
<a routerLink ="./home">Home</a>
</li>
<li class="active">
<a routerLink="./login">LogIn</a>
</li>
<li>
<a routerLink="./logout">Log out</a>
</li>
</ul>
</div>
</nav>
</header>
<main>
<router-outlet></router-outlet>
</main>
When i compile the program i am getting an error as
EXCEPTION: Uncaught (in promise): Error: Cannot match any routes: ''
Can anyone help me in solving this issue
Thanks in advance
Try setting up some base global routes including an empty route and a catch all route.
Here's an example app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { PageNotFoundComponent } from './page-not-found.component';
const appRoutes: Routes = [
{
path: '',
redirectTo: '/login',
pathMatch: 'full'
},
{ path: '**', component: PageNotFoundComponent }
];
@NgModule({
imports: [
RouterModule.forRoot(appRoutes, { enableTracing: true })
],
exports: [
RouterModule
]
})
export class AppRoutingModule { }
This is the app.module.ts
import { AppRoutingModule } from './app-routing.module';
...
@NgModule({
imports: [
...
AppRoutingModule // Make sure this one is last
],
bootstrap: [AppComponent]
})
export class AppModule { }
The PageNotFoundComponent
is displayed in the <router-outlet>
(it's a basic component) whenever the route doesn't match any previously defined route and the ''
path matches the empty route (localhost:4200/
).
You will want your AppRoutingModule
imported last in your AppModule
because the router matches routes in the order that they are registered. By importing the 'matches anything' route last you will be sure all other routes are checked first.
Set enableTracing
to true for your routes to help debug navigation changes while developing.
This should be a good place to start
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With