angular传参的两种模式

第一种,使用path/router?id=的模式

跳转页面的入口

1
<a [routerLink]="['/product']" [queryParams]="{id:1}">PRODUCT</a>

被跳转页面的控制器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {

private productId:number;
constructor(
private routeInfo: ActivatedRoute
) { }

ngOnInit() {
this.productId = this.routeInfo.snapshot.queryParams["id"];
}

}

第二种,使用path/id的模式

路由配置文件

1
2
3
4
5
const routes: Routes = [
{path:'',component:HomeComponent},
{path:'product/:id',component:ProductComponent},
{path:'**',component:Code404Component}
;

跳转页面

1
<a [routerLink]="['/product',1]">PRODUCT</a>

被跳转控制器,参数快照模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {

private productId:number;
constructor(
private routeInfo: ActivatedRoute
) { }

ngOnInit() {
this.productId = this.routeInfo.snapshot.params["id"];
}

}

跳转控制器

1
this.router.navigate(['/product',3]);

被跳转控制器,参数订阅模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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 {

private productId:number;
constructor(
private routeInfo: ActivatedRoute
) { }

ngOnInit() {
this.routeInfo.params.subscribe(
(params:Params) => this.productId = params["id"]
)
}

}