使用Anglar Router導(dǎo)航
- 路由基礎(chǔ),路由相關(guān)對(duì)象
- Routes 路由配置,保存著url對(duì)應(yīng)展示哪個(gè)組件,以及在哪個(gè)RouterOutlet中展示組件
- RouterOutlet 在HTML中標(biāo)記路由內(nèi)容呈現(xiàn)位置的占位符指令
- Router 負(fù)責(zé)在運(yùn)行時(shí)執(zhí)行路由對(duì)象,可以通過調(diào)用其navigate()和navigateByUrl()方法來導(dǎo)航到一個(gè)指令的路由
- RouterLink在HTML中聲明路由導(dǎo)航用的指令
- ActivatedRoute 當(dāng)前激活路由對(duì)象,保存路由信息,如路由地址,路由參數(shù)
- 新建一個(gè)路由項(xiàng)目,并生成一個(gè)home組件和一個(gè)product組件
ng new router –routing
ng g component home
ng g component product
- 會(huì)額外生成一個(gè)app-routing-module.ts模塊,在主模塊的import會(huì)導(dǎo)入一個(gè)AppRoutingModule,在路由模塊中配置路由
import {HomeComponent} from './home/home.component'
import {ProductComponent} from './product/product.component'
const routes: Routes = [
{path:'',component:HomeComponent},
{path:'product',component:ProductComponent}
];
- 使用路由進(jìn)行導(dǎo)航()表示事件綁定,表示綁定click事件(類似vue的@)
<a [routerLink]="['/']">主頁</a>
<a [routerLink]="['/product']">商品詳情</a>
<input type="button" value="商品詳情" (click)="toProductDetails()">
<router-outlet></router-outlet>
- 使用綁定的click跳轉(zhuǎn)路由
export class AppComponent {
title = 'route';
constructor(private router:Router) {
}
toProductDetails() {
this.router.navigate(['/product'])
}
}
- 通過這樣的配置,當(dāng)用戶訪問不存在的地址時(shí),頁面顯示code404組件的內(nèi)容(在設(shè)置這個(gè)路由時(shí),要把這個(gè)通配符的路由放到最后,因?yàn)樗亲钔ㄓ玫穆酚?,只有?dāng)路由匹配不到時(shí),才能夠讓其匹配)
{path:'**',component:Code404Component},
在路由時(shí)傳遞數(shù)據(jù)
- 在查詢參數(shù)中傳遞數(shù)據(jù),/product?id=1&name=2通過ActivatedRoute.queryParams[id],獲取id的值
- 在商品詳情組件中接收主界面?zhèn)鬟f的商品的id
<a [routerLink]="['/product']" [queryParams]="{id:1}">商品詳情</a>
export class ProductComponent implements OnInit {
private productId:number
constructor( private routeInfo:ActivatedRoute){
}
ngOnInit(){
this.productId=this.routeInfo.snapshot.queryParams["id"] }
}
- 在路由的路徑中傳遞數(shù)據(jù),{path:/product/:id} => /product/1,ActivatedRoute.params[id]獲取id
<a [routerLink]="['/product',1]">商品詳情</a>
export class ProductComponent implements OnInit {
private productId:number
constructor( private routeInfo:ActivatedRoute){
}
ngOnInit(){
this.productId=this.routeInfo.snapshot.params["id"] }
}
- 參數(shù)快照snapshot,這個(gè)方法的弊端是只有在組件在被創(chuàng)建時(shí)才會(huì)被調(diào)用一次,如果其他路徑也會(huì)定位到這個(gè)組件中時(shí),點(diǎn)擊原本的導(dǎo)航將不會(huì)改變獲取的id可以通過參數(shù)訂閱來解決,將ngOnInit修改
this.routeInfo=this.subscribe((params:Params)=>this.productId=params["id"])
- 在路由配置中傳遞數(shù)據(jù),{path:'product',component:ProductComponent,data:[{isProd:true}]},ActivatedRoute.data[0][isProd]來獲取isProd的值
重定向路由
- 在用戶訪問一個(gè)特定的地址時(shí),將其重定向到另一個(gè)指定地址
const routes: Routes = [
{path:'',redirectTo:'/home',pathMatch:'full'},
{path:'home',component:HomeComponent},
{path:'product',component:ProductComponent},
{path:'**',component:Code404Component},
];