1.路由配置
- 創(chuàng)建兩個(gè)組件
- 在app-routing.modult.ts中配一個(gè)空路由
const routes: Routes = [
{path: '', component: HomeComponent}
];
在做路由配置時(shí)path屬性不要用’/'開頭,因?yàn)閍ngular本身會(huì)根據(jù)path的值做相應(yīng)的解析生成url。
- 在app.component.html中自動(dòng)加入<router-outlet></router-outlet>
- link訪問(wèn)路由寫法:<a [routerLink]="['/']">主頁(yè)</a>
- 通過(guò)調(diào)用方法訪問(wèn)路由的寫法
<input type="button" value="我是詳情" (click)="toStockDetail()">
方法在app.component.ts中聲明:
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){
}
toStockDetail(){
this.router.navigate(['/stock']);
}
}
- 當(dāng)用戶訪問(wèn)的路由不存在時(shí),頁(yè)面出錯(cuò),可以通過(guò)配置通配符解決問(wèn)題。
創(chuàng)建一個(gè)新的組件,在路由配置中加{path: '**', component: Code404Component}
通配符寫在整個(gè)路由配置的最后面。
2.數(shù)據(jù)傳遞
1.在查詢參數(shù)中傳遞數(shù)據(jù)
- 路由路徑?參數(shù)名=參數(shù)值
- /product?id=1&name=2 => ActivatedRoute.queryParams[id]
2.在路由路徑中傳遞數(shù)據(jù)
- 指定路由路徑加參數(shù)名=>在實(shí)際路徑中攜帶的參數(shù)=>調(diào)用
- {path:/product/:id}=>/product/1=>ActivatedRoute.params[id]
3.在路由配置中傳遞數(shù)據(jù)
- 通過(guò)data參數(shù)定義靜態(tài)數(shù)據(jù),data本身為數(shù)組
- {path: /product, component: ProductComponent, data:[{isProd:true}]}=>ActivatedRoute.data[0][isProd]
4.在url中傳遞參數(shù)
- 修改路由配置中的path屬性,使其可以攜帶參數(shù)。
- {path: 'stock/:id', component: ProductComponent, data:[{isPro:true}]}
- 修改路由鏈接,讓鏈接在跳轉(zhuǎn)時(shí)攜帶參數(shù)。
- <a [routerLink]= "['/stock',1]" >url獲取參數(shù)</a>
3.參數(shù)快照與參數(shù)訂閱
- 參數(shù)快照:傳參方式與前面記錄相同。當(dāng)從主頁(yè)跳轉(zhuǎn)到詳情頁(yè)時(shí),詳情頁(yè)組件被創(chuàng)建,調(diào)用ngOnInit()方法,但是,當(dāng)詳情頁(yè)跳轉(zhuǎn)到詳情頁(yè)時(shí)(兩個(gè)傳參不同),組件不會(huì)被重新創(chuàng)建,ngOnInit()方法在同一組件路由到自身時(shí)不會(huì)被調(diào)用。
this.id = this.routerInfo.snapshot.params["id"]
- 參數(shù)訂閱:訂閱方式改變參數(shù)值時(shí),每當(dāng)路由參數(shù)變換時(shí),匿名的方法都會(huì)被調(diào)用一次。
this.routerInfo.params.subscribe((params:Params)=>this.id = params["id"])
4.重定向路由
{path: '', redirectTo: '/home',pathMatch:'full'}
pathMatch:'full'表示只有訪問(wèn)路徑是精準(zhǔn)的空字符串時(shí)才跳轉(zhuǎn)到/home上。
{path: 'xx', redirectTo: '/home',pathMatch:'prefix'}
pathMatch:'prefix'表示路徑是以“xx”開頭就可跳轉(zhuǎn)到/home上。
5.子路由
在原有路由的基礎(chǔ)上加children屬性。將router-outlet聲明在哪個(gè)子路由就會(huì)顯示在哪兒。由于聲明的是子路由,在訪問(wèn)子路由時(shí)是不能以“/”開頭的,“/”開頭代表在主路由中找,子路由以“./”開頭。
- 子路由可以一直嵌套
- 路由信息和組件是分離的
{path: 'stock', component: StockComponent,
children:[
{path: '', component:BuyerListComponent},
{path: 'seller/:id', component:SellerListComponent}
]
}
6.輔助路由
在每個(gè)頁(yè)面都有的一些側(cè)邊導(dǎo)航,會(huì)用到輔助路由。
- 在組件模板上除了外,還需要聲明一個(gè)帶name屬性的
- 在路由配置中去配置aux可以顯示哪些組件。
{path: 'consult', component: ConsultComponent,outlet:"aux"}
- 導(dǎo)航時(shí)指定在路由到某個(gè)地址時(shí),輔助路由上需要顯示哪個(gè)組件。
<a [routerLink]="[{outlets: {aux: 'consult'}}]">開始</a><br>
說(shuō)明:主路由的內(nèi)容也可以控制,主路由沒(méi)有設(shè)置名字,它有一個(gè)默認(rèn)的關(guān)鍵字——primary,在aux前面加上primary:'home',然后點(diǎn)擊,主路由跳轉(zhuǎn)到home。