如何使用NavigationExtras动态传递酒店数据?Angular路由传参问题
解决Angular点击酒店标题动态传递对应酒店数据到详情页的问题
这问题我之前做项目时也碰到过,其实核心就是把当前循环的酒店对象传递给点击事件,就能动态获取对应数据了,具体步骤如下:
1. 修改模板中的点击事件
把原来的点击事件改成传递当前迭代的hotel对象,这样点击时就能把对应酒店的所有数据传给方法:
<div *ngFor="let hotel of hotelList"> <h5 (click)="getHotelDetails(hotel)">{{hotel.hotel_name}}</h5> <span class="ratingStyle"></span> </div>
2. 更新getHotelDetails方法
让方法接收hotel参数,然后从这个参数里动态提取你需要的字段,构建navigationExtras的state:
getHotelDetails(hotel: any) { // 从当前点击的酒店对象中动态获取数据 let navigationExtras: NavigationExtras = { state : { api: hotel.api, trace_id: hotel.trace_id, token_id: hotel.token_id, hotel_code: hotel.hotel_id, result_index: hotel.hotel_index.toString() // 转成字符串匹配你原来的格式 } }; this.router.navigate(['hoteldetail'], navigationExtras); }
3. (可选)详情页接收传递的状态数据
如果需要在详情页拿到这些数据,通过ActivatedRoute的snapshot.state就能获取:
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-hotel-detail', templateUrl: './hotel-detail.component.html' }) export class HotelDetailComponent implements OnInit { hotelData: any; constructor(private route: ActivatedRoute) {} ngOnInit() { const navigationState = this.route.snapshot.state; if (navigationState) { this.hotelData = navigationState; // 这里就可以用this.hotelData里的字段渲染详情页了 } } }
完整修改后的组件代码参考
import { Component, OnInit } from '@angular/core'; import { Router, NavigationExtras } from '@angular/router'; import { HotelService } from './your-hotel-service-path'; @Component({ selector: 'app-hotel-list', templateUrl: './hotel-list.component.html' }) export class HotelListComponent implements OnInit { hotelList: Array<any> = []; constructor( private hotelService: HotelService, private router: Router ) {} ngOnInit() { this.hotelService.getHotelsearch().subscribe( (res) => { this.hotelList = res; }, (err) => { console.error('获取酒店列表失败:', err); } ); } getHotelDetails(hotel: any) { let navigationExtras: NavigationExtras = { state : { api: hotel.api, trace_id: hotel.trace_id, token_id: hotel.token_id, hotel_code: hotel.hotel_id, result_index: hotel.hotel_index.toString() } }; this.router.navigate(['hoteldetail'], navigationExtras); } }
原理说明
在*ngFor循环中,每个hotel都是数组里的当前迭代元素,把它作为参数传给点击事件后,方法里就能直接访问该酒店的所有属性,完美替代原来的静态值,实现动态传递对应酒店的数据。
内容的提问来源于stack exchange,提问作者swetha
相关产品推荐
相关产品推荐

