Angular的学习使用过程中,路由跳转支撑了项目的全过程,所以路由跳转是一个很常见也是一个很容易忽略的点,,对于页面之间的跳转有着很多的问题,跳转的方式/如何携带参数跳转,下面是自己在学习过程中对angular路由跳转的总结(angular7)
路由跳转的第一种方式-导航式跳转
第一种:该指令接收一个链接参数数组,Angular将根据该数组来生成UrlTree实例进行跳转。使用routerLink跳转,在标签的写入将将要跳转的页面路径写在【】中,
<div routerLink="['/path']"></div>
如果有需要再路由跳转的时候携带某些指定的参数,例如:id/ 在对应的ts文件中声明一个id,将申明的id写在传递参数queryParams对象中
<div routerLink="['/path']" [queryParams]="{id:key}" >跳转</div>
点击标签跳转以后获取传过来的参数 注意:接收时通过 queryParams 进行接收
首先引入
import {ActivatedRoute} from '@angular/router' 再声明: constructor(public route:ActivatedRoute) { }
接收: // 接收传过来的值 ngOnInit() { this.route.queryParams.subscribe((res)=>{ console.log(res) }) }
第二种:动态路由传值这种情况是在浏览器中可以显示对应的参数 这种的是斜杆
在路由文件中进行配置path: 'devicepay/:id'
*/:id必传
{ path: 'devicepay/:id',component:DevicepayComponent},
在html界面中进行跳转
<a [routerLink]="['/devicepay/',key]">
在另一界面中接收传过来的参数 注意 :动态路由接收时使用的是 params
方法同上
引入
import {ActivatedRoute} from '@angular/router' 再声明 constructor(public route:ActivatedRoute) { 接收: // 接收传过来的值 route.params.subscribe((res)=>{ console.log(res) }) }
路由跳转的第一种方式-编程式跳转
第三种:动态js进行跳转 主要在方法对象中使用
html 中 注意里面传入的i值是 循环中 获取的索引值i
<li *ngFor="let item of resList ;let i=index"> <button (click)='gotoDevicePay(i)'>跳转到支付界面</button> </li>
在路由文件中进行配置
{ path: 'devicepay',component:DevicepayComponent},
js中 进行路由跳转还是先引入----再声明
定义点击事件
gotoDevicePay(key){ this.router.navigate(['/devicepay/'],{queryParams:{id:key}})//跳转路径 实现的是动态跳转数据 }
第四种:通过get方式可以传入多个参数到下一界面
引入 NavigationExtras
import { Router ,NavigationExtras} from '@angular/router';
定义一个 goNewsContent 方法执行跳转 , 用 NavigationExtras
goNewsContent(){ let navigationExtras: NavigationExtras = { queryParams: { 'session_id': '123' }, fragment: 'anchor' }; this.router.navigate(['/news'],navigationExtras); }
获取跳转过来的页面接受传过来的值
constructor(private route: ActivatedRoute) { console.log(this.route.queryParams); }