一、路由傳參
代碼接上次 的帶routing的demo
1、查詢參數(shù)傳參
路由配置:
{path: 'product', component: ProductComponent},
app.component.html頁(yè)面中的a標(biāo)簽修改
<a [routerLink]="['/product']" [queryParams]="{id:1}"> 產(chǎn)品1</a>
<a [routerLink]="['/product']" [queryParams]="{id:3}"> 產(chǎn)品2</a>
在調(diào)用路由的a標(biāo)簽里面添加queryParams
在控制器中添加參數(shù)的獲取
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Params} from '@angular/router';
@Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
public productId: number;
constructor(private routerInfo: ActivatedRoute ) { }
ngOnInit() {
console.log('init');
// 以下是訂閱的方式獲取參數(shù) 當(dāng)參數(shù)變化的時(shí)候回調(diào)用匿名函數(shù)修改變量
this.routerInfo.queryParams.subscribe((params: Params) => {
this.productId = params['id'];
});
// 以下下獲取參數(shù)是通過(guò)快照的方式獲取的。
// 快照方式在路由相同的情況下(這里指的相同是 路由中的配置相同)
// 不會(huì)重復(fù)創(chuàng)建組件。從而使得onInit方法只會(huì)在路由初始化的時(shí)候創(chuàng)建一次。參數(shù)無(wú)法更新。
// this.productId = this.routerInfo.snapshot.queryParams['id'];
}
}
這樣就實(shí)現(xiàn)了路由使用查詢參數(shù)傳參。
2、查詢路徑傳參傳參
路由配置:
{path: 'product/:id', component: ProductComponent},
這樣是通過(guò)路由配置來(lái)傳參
在app.component.html頁(yè)面中修改
<a [routerLink]="['/product/3']"> 產(chǎn)品3</a>
在product.component.ts中修改 與第一種方法對(duì)比的話。這里的訂閱參數(shù)是params 而不是 queryParams
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Params} from '@angular/router';
@Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
public productId: number;
constructor(private routerInfo: ActivatedRoute ) { }
ngOnInit() {
console.log('init');
// 以下是訂閱的方式獲取參數(shù) 當(dāng)參數(shù)變化的時(shí)候回調(diào)用匿名函數(shù)修改變量
this.routerInfo.params.subscribe((params: Params) => {
this.productId = params['id'];
});
// 以下下獲取參數(shù)是通過(guò)快照的方式獲取的。
// 快照方式在路由相同的情況下(這里指的相同是 路由中的配置相同)
// 不會(huì)重復(fù)創(chuàng)建組件。從而使得onInit方法只會(huì)在路由初始化的時(shí)候創(chuàng)建一次。參數(shù)無(wú)法更新。
this.productId = this.routerInfo.snapshot.params['id'];
}
}
2、配置靜態(tài)數(shù)據(jù)傳參(估計(jì)不會(huì)怎么用到)
修改路由配置
{path: 'product_data', component: ProductComponent, data : [{id: 4}]},
在app.component.html頁(yè)面中修改
<a [routerLink]="['/product_data']" > 產(chǎn)品4</a>
在product.component.ts中修改
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Data, Params} from '@angular/router';
@Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
public productId: number;
constructor(private routerInfo: ActivatedRoute ) { }
ngOnInit() {
console.log('init');
this.productId = this.routerInfo.snapshot.data[0]['id'];
}