模块是基础,接下来看一下路由,路由就是整个项目的一根线,串联着各个项目的各个模块。
还是用例子来记录,看图说话。
先准备几个组件
创建项目
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>
这里就完成了路由的配置
来源:https://www.cnblogs.com/bh4lm/p/6639133.html