1.路由配置
- 創(chuàng)建兩個組件
- 在app-routing.modult.ts中配一個空路由
const routes: Routes = [
{path: '', component: HomeComponent}
];
在做路由配置時path屬性不要用’/'開頭良哲,因為angular本身會根據(jù)path的值做相應(yīng)的解析生成url铸题。
- 在app.component.html中自動加入<router-outlet></router-outlet>
- link訪問路由寫法:<a [routerLink]="['/']">主頁</a>
- 通過調(diào)用方法訪問路由的寫法
<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)用戶訪問的路由不存在時歼秽,頁面出錯筒繁,可以通過配置通配符解決問題。
創(chuàng)建一個新的組件静檬,在路由配置中加{path: '**', component: Code404Component}
通配符寫在整個路由配置的最后面帘营。
2.數(shù)據(jù)傳遞
1.在查詢參數(shù)中傳遞數(shù)據(jù)
- 路由路徑?參數(shù)名=參數(shù)值
- /product?id=1&name=2 => ActivatedRoute.queryParams[id]
2.在路由路徑中傳遞數(shù)據(jù)
- 指定路由路徑加參數(shù)名=>在實際路徑中攜帶的參數(shù)=>調(diào)用
- {path:/product/:id}=>/product/1=>ActivatedRoute.params[id]
3.在路由配置中傳遞數(shù)據(jù)
- 通過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ù)冗荸。
- <a [routerLink]= "['/stock',1]" >url獲取參數(shù)</a>
3.參數(shù)快照與參數(shù)訂閱
- 參數(shù)快照:傳參方式與前面記錄相同。當(dāng)從主頁跳轉(zhuǎn)到詳情頁時利耍,詳情頁組件被創(chuàng)建蚌本,調(diào)用ngOnInit()方法,但是隘梨,當(dāng)詳情頁跳轉(zhuǎn)到詳情頁時(兩個傳參不同)程癌,組件不會被重新創(chuàng)建,ngOnInit()方法在同一組件路由到自身時不會被調(diào)用轴猎。
this.id = this.routerInfo.snapshot.params["id"]
- 參數(shù)訂閱:訂閱方式改變參數(shù)值時嵌莉,每當(dāng)路由參數(shù)變換時,匿名的方法都會被調(diào)用一次捻脖。
this.routerInfo.params.subscribe((params:Params)=>this.id = params["id"])
4.重定向路由
{path: '', redirectTo: '/home',pathMatch:'full'}
pathMatch:'full'表示只有訪問路徑是精準(zhǔn)的空字符串時才跳轉(zhuǎn)到/home上锐峭。
{path: 'xx', redirectTo: '/home',pathMatch:'prefix'}
pathMatch:'prefix'表示路徑是以“xx”開頭就可跳轉(zhuǎn)到/home上。
5.子路由
在原有路由的基礎(chǔ)上加children屬性郎仆。將router-outlet聲明在哪個子路由就會顯示在哪兒只祠。由于聲明的是子路由,在訪問子路由時是不能以“/”開頭的扰肌,“/”開頭代表在主路由中找抛寝,子路由以“./”開頭。
- 子路由可以一直嵌套
- 路由信息和組件是分離的
{path: 'stock', component: StockComponent,
children:[
{path: '', component:BuyerListComponent},
{path: 'seller/:id', component:SellerListComponent}
]
}
6.輔助路由
在每個頁面都有的一些側(cè)邊導(dǎo)航,會用到輔助路由盗舰。
- 在組件模板上除了外晶府,還需要聲明一個帶name屬性的
- 在路由配置中去配置aux可以顯示哪些組件。
{path: 'consult', component: ConsultComponent,outlet:"aux"}
- 導(dǎo)航時指定在路由到某個地址時钻趋,輔助路由上需要顯示哪個組件川陆。
<a [routerLink]="[{outlets: {aux: 'consult'}}]">開始</a><br>
說明:主路由的內(nèi)容也可以控制,主路由沒有設(shè)置名字蛮位,它有一個默認(rèn)的關(guān)鍵字——primary较沪,在aux前面加上primary:'home',然后點擊失仁,主路由跳轉(zhuǎn)到home尸曼。