目前Angular已经升级到了稳定版本Angular5,在这次升级中也对路由有一些改变。现在对于路由传值进行详解,首先一种方式是官网的导航到详情的单值id传入,另一种是多数据传入!

一、单值传入

以前跳转页面的时候,如果要传递参数都是在ts文件里写,现在可以直接在html页面直接传递参数。

list.component.html
  • html
1
<p *ngFor="let item of items" [routerLink]="['/listDetail',item.id]"></p>

然后是配置路由:(单值传入的方式需要在详情组件路由配置)

list.routing.module.ts
  • ts
1
2
3
4
{
path:'listDetail/:id', // :后面就是传递的参数
component:ListDetailComponent
},

传入后就是取到参数,在详情组件的ngOnInit生命周期获取参数

list-detail.component.html
  • ts
1
2
3
4
5
6
7
8
9
ngOnInit() {
this.route.params
.subscribe((params: Params) => {
this.id = params['id'];
console.log(this.id);
console.log('传值');
console.log(params)
});
}

二、多值传入

我们在平时的复杂的业务场景我们需要传多个数据,这时候该怎么办呢?这时候我们就用到了queryParams。

list.component.html
  • html
1
2
<p *ngFor="let data of datas" [routerLink]="['/listDetails']"
[queryParams]="{id:data.id,state:data.state}"></p>

这里数据我是直接拿上去的,同样你可以组织好数据,一个参数放上去,简化html结构,现在有个问题,这样多值传入路由参数怎么配置呢?/:id/:state???我这个参数多少也不是固定的咋办?

其实这种方式不需要配置路由!你只需要传入和取到数据就可以了!

获取参数也只需要把params改成queryParams就可以了

list-detail.component.html
  • ts
1
2
3
4
5
6
7
8
9
10
ngOnInit() {
this.route.queryParams
.subscribe((params: Params) => {
this.id = params['id'];
this.state = params['state'];
console.log(params)
console.log(this.id);
console.log(this.state);
});
}