ng路由传参
2018-08-23 本文已影响0人
阿飞_1217
angular的路由传递参数一共有三种方式 固定参数、动态路由参数、查询参数三种叫法是本人习惯叫法 非官方 仅供参考
每一种传递参数的接收方式又分两种 参数快照、参数订阅
固定参数
页面URL: http;//localhost:4200/dataAdd/shopAdd
1. 路由配置
-
固定参数-路由配置.png
2. 路由跳转
-
html写法
html跳转.png
-
ts组件写法
js组件跳转
3 接收参数
-
参数快照
参数快照.png
-
参数订阅
参数订阅.png
动态路由参数
页面URL: http;//localhost:4200/dataAdd/shopAdd/2
1.动态路由配置
-
动态路由配置.png
2. 路由跳转
-
html写法
html传参.png
- ts写法
this.router.navigate(['/dataAdd/shpoAdd',2]);
3 接收参数
- 参数快照
let snapshotData = this.activeRoute.snapshot.params["id"];
- 参数订阅
this.activeRoute.params.subscribe(data => {
console.log(data);
})
查询参数
页面URL: http;//localhost:4200/dataAdd/shopAdd?id=1&name=afei
和传统的URL一样
1. 路由不用配置
2.路由跳转
- html写法
<li routerLink="dataAdd/shopAdd" [queryParams]="{id:1,name:'afei'}" nz-menu-item>添加商铺</li>
- ts写法
this.router.navigate(['/dataAdd/shpoAdd'],{queryParams:{id: 1,name: 'afei'}});
3 接收参数
- 参数快照
let snapshotData = this.activeRoute.snapshot.queryParams["id"];
- 参数订阅
this.activeRoute.queryParams.subscribe(data => {
console.log(data);
})
总结:
传递参数共3种方式 data、params、queryParams 3种对应的URL也不一样。 当然 3种方式可以混合使用。
多说两句
参数快照 和 参数订阅 区别
问题主要发生在 同一个组件的跳转 如下
URL: http;//localhost:4200/dataAdd/shopAdd/2 跳转
URL: http;//localhost:4200/dataAdd/shopAdd/3
当我们从shopAdd组件又调到shopAdd组件时,由于在shopAdd组件已经被创建过一次了,所以constructor()方法不会被调用,所以oninit方法也不会再调用 ,所以id属性依然保持着第一次被创建时赋予的值。
// 使用快照的方式 id 并没有及时的更新
let id = this.activeRoute.snapshot.params["id"];
//使用订阅的方式 观察者模式一直在监听params参数 能及时的更新
this.activeRoute.params.subscribe(params => {
console.log(params.id);
})
遗留疑惑:
参数订阅 组件销毁时是否需要取消订阅 我也不晓得了。