模塊是基礎,接下來看一下路由,路由就是整個項目的一根線,串聯着各個項目的各個模塊。
還是用例子來記錄,看圖說話。

先准備幾個組件
創建項目
ng new routestest
創建組件
ng g c one-component
ng g c two-component
ng g c page-not-found-component
創建對應的module的routes模塊
ng g m app-routes

app-routes.module.ts文件
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { OneComponentComponent } from './one-component/one-component.component';
import { TwoComponentComponent } from './two-component/two-component.component';
import { PageNotFoundComponentComponent } from './page-not-found-component/page-not-found-component.component';
export const appRoutes = [
{
path: '',
redirectTo: 'one',
pathMatch: 'full'
},
{
path: 'one',
component: OneComponentComponent
},
{
path: 'two',
component: TwoComponentComponent
},
{
path: '**', //fallback router must in the last
component: PageNotFoundComponentComponent
}
];
@NgModule({
declarations: [
OneComponentComponent,
TwoComponentComponent,
PageNotFoundComponentComponent
],
imports: [
RouterModule.forRoot(appRoutes)
],
exports: [
RouterModule
]
})
export class AppRoutesModule { }
app.module.ts文件
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppRoutesModule } from './app-routes.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AppRoutesModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.html文件
<h1>
{{title}}
</h1>
<nav>
<a routerLink='one'>one</a>
<a routerLink='two'>two</a>
<a routerLink='three'>three</a>
</nav>
<router-outlet></router-outlet>
這里就完成了路由的配置

