使用一下命令新建一個項目:css
ng new router --routing // 不加-routing參數,能夠在app.module.ts配置路由
生成項目時添加了–routing參數後,會多生成一個app-routing.module.ts文件:html
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; const routes: Routes = [ { path:'', children: [] } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], providers:[] }) export class AppRoutingModule { }
在app.module.ts中也會多引入AppRoutingModule:bootstrap
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import {FormsModule} from '@angular/forms'; import {HttpModule} from '@angular/http'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, FormsModule, HttpModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
在app.component.html中會加入router-outletapp
<h1> {{title}} </h1> <router-outlet></router-outlet>
新生成兩個組件ng g component home,ng g component productide
而後修改app-routing.modules.ts,爲了保證通用性,這裏寫地址的時候不要在前面加上/this
const routes: Routes = [ {path:'',component:HomeComponent}, {path:'product',component:ProductComponent} ];
修改app.component.htmlcode
<a [routerLink]="['/']">主頁</a> <a [routerLink]="['/product']">商品詳情</a> <router-outlet></router-outlet>
此時,當你訪問localhost:4200的時候顯示的是home works!,當你點擊商品詳情,會顯示product works!而且地址變成了localhost:4200/productcomponent
修改app.component.html和app.component.tsorm
<a [routerLink]="['/']">主頁</a> <a [routerLink]="['/product']">商品詳情</a> <input type="button" value="商品詳情" (click)="toProductDetails()"> <router-outlet></router-outlet>
import { Component } from '@angular/core'; import {Router} from "@angular/router"; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; constructor(private router: Router){} toProductDetails(){ this.router.navigate(['/product']); } }
運行程序,點擊按鈕,下邊就會顯示product works!router
新生成一個組件ng g component code404
修改app-routing.module.ts
const routes: Routes = [ {path:'',component:HomeComponent}, {path:'product',component:ProductComponent}, {path:'**',component:Code404Component} ];
當訪問一個不存在的路徑時會顯示code404 works!
顯示路由是從上往下匹配地址,若是把{path:’**’,component:Code404Component}放到前面無論訪問那個頁面都會顯示code404了。因此具備通用性的路由要放到最後邊。