1.在查询参数中传递数据
- <a [routerLink]="['/product']" [queryParams]="{id:1,name:'dongian'}">product</a>
然后在app-routing.module.ts中配置
- const routes: Routes = [
- {path: 'product', component: ProductComponent}
- ];
最后在product.component.ts中接收参数
- private productShop: any = {};
- constructor(private routeInfo: ActivatedRoute ) { }
- ngOnInit() {
- this.routeInfo.queryParams.subscribe(queryParams => {
- this.productShop.id = queryParams.id;
- this.productShop.name = queryParams.name;
- });
- }
当然记得 ActivatedRoute是需要注入。。。在页面就可以打印出来了
2.路由路径中传递参数 (在这里我会将2种参数接收方式)
- <a [routerLink]="['/product',1]">product</a>
然后在app-routing.module.ts中配置
- const routes: Routes = [
- {path: 'product/:id', component: ProductComponent}
- ];
最后在product.component.ts中接收参数
第一种 也称作 参数快照
- private productShop: number;
- constructor(private routeInfo: ActivatedRoute ) { }
- ngOnInit() {
- this.productShop = this.routeInfo.snapshot.params['id'];
- }
第二种 也称作 参数订阅
- private productShop: any;
- constructor(private routeInfo: ActivatedRoute ) { }
- ngOnInit() {
- this.routeInfo.params.subscribe(params => this.productShop = params['id']);
- }
区别也就在于url地址相同,传递参数不同时(比如说,一个是a标签方式跳转,一个是点击事件的方式跳转,2种情况同时存在时),使用第二种方法,
不存在这种情况的时候使用可以使用第一种
3.路由配置中传递参数(当然也要2中写法)
- onProduct() {
- this.router.navigate(['product', 2]);
- }
这里主要讲第二种
- <button (click)="onProduct()">商品详情</button>
- onProduct() {
- this.router.navigate(['product'], {queryParams: {id: 2, name: 'dongtian'}});
- }
- private productShop: any = {};
- constructor(private routeInfo: ActivatedRoute ) { }
- ngOnInit() {
- this.routeInfo.queryParams.subscribe( queryParams => {
- this.productShop.id = queryParams.id;
- this.productShop.name = queryParams.name;
- });
- }