Angular 4中router.navigate路由跳转如何隐藏URL参数?
隐藏Angular 4路由跳转参数的实用方案
嘿,在Angular 4里想要隐藏路由跳转时URL携带的参数,我给你两种靠谱的解决方案,都是实际项目里常用的:
一、使用共享服务传递动态参数(推荐)
这种方法是把需要传递的参数存在内存中的共享服务里,路由跳转时URL只显示目标路径,不会带上任何参数,完美满足你的需求。
步骤1:创建一个共享服务
先新建一个专门用来传递参数的服务,比如ReservationDataService:
// reservation-data.service.ts import { Injectable } from '@angular/core'; @Injectable() export class ReservationDataService { // 用来存储跳转需要的参数 private reservationParams: any = {}; // 存入参数的方法 setParams(params: any): void { this.reservationParams = { ...params }; } // 获取参数的方法 getParams(): any { return this.reservationParams; } }
别忘了把这个服务添加到你的AppModule的providers数组里,这样整个应用都能注入使用。
步骤2:在跳转组件中存入参数并导航
修改你原来的onClickMe方法,先把参数存入服务,再跳转到目标路由(不带任何参数):
// 你的跳转组件.ts文件 import { Router } from '@angular/router'; import { ReservationDataService } from './reservation-data.service'; // 构造函数注入服务和路由 constructor( private router: Router, private reservationDataService: ReservationDataService ) {} onClickMe(id): void { const decimal = this.date.getMonth() + 1; // 整理需要传递的所有参数 const transferParams = { nembPerson: this.nembPerson, timereservation: this.timereservation, day: this.date.getDate(), month: decimal, year: this.date.getFullYear(), id: id }; // 把参数存入服务 this.reservationDataService.setParams(transferParams); // 导航到RestaurantView,URL只会显示 /RestaurantView this.router.navigate(['/RestaurantView']); }
步骤3:在目标组件中获取参数
在RestaurantViewComponent里,从服务中取出之前存入的参数:
// RestaurantViewComponent.ts import { OnInit } from '@angular/core'; import { ReservationDataService } from './reservation-data.service'; export class RestaurantViewComponent implements OnInit { constructor(private reservationDataService: ReservationDataService) {} ngOnInit(): void { // 获取传递过来的参数 const params = this.reservationDataService.getParams(); // 这里就可以使用参数了,比如打印出来看看 console.log('预约人数:', params.nembPerson, '餐厅ID:', params.id); } }
注意:这种方法的参数是存在内存中的,如果用户刷新页面,参数会丢失。如果需要刷新后参数依然保留,可以在服务里结合localStorage或sessionStorage来存储参数,修改一下setParams和getParams方法即可。
二、可选方案:使用skipLocationChange(不更新URL)
如果你不需要URL跳转到/RestaurantView,只是想加载对应的组件但保持当前URL不变,可以用NavigationExtras的skipLocationChange选项:
onClickMe(id): void { const decimal = this.date.getMonth() + 1; this.router.navigate( ['/RestaurantView'], { skipLocationChange: true } ); }
不过要注意,Angular 4没有路由state属性来传递动态参数,所以这种场景下依然推荐搭配共享服务来传递数据,skipLocationChange仅用来实现URL不更新的效果。
内容的提问来源于stack exchange,提问作者Ghazi Gassara
相关产品推荐
相关产品推荐

