You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中如何将经纬度参数传递到其他路由组件?

Angular跨路由组件参数传递实现方案

以下为适配你当前场景的两种可直接落地的实现方式:

方案1:路由状态传参(参数不暴露在URL,推荐当前场景使用)

第一步:修改home.component.ts跳转逻辑

将你原有代码里的this.router.navigate(["/stations"])替换为以下代码:

this.router.navigate(["/stations"], {
  state: {
    lat: lat,
    lng: long
  }
})

第二步:修改stations.component.ts接收参数

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-stations',
  templateUrl: './stations.component.html'
})
export class StationsComponent implements OnInit {
  lat?: number;
  lng?: number;

  constructor(private router: Router) {}

  ngOnInit(): void {
    const navigation = this.router.getCurrentNavigation();
    const state = navigation?.extras.state as {lat: number, lng: number};
    if (state) {
      this.lat = state.lat;
      this.lng = state.lng;
      // 拿到坐标后直接执行后续计算逻辑即可
    }
  }
}

方案2:查询参数传参(参数暴露在URL,适合需要分享路由链接的场景)

第一步:修改home.component.ts跳转逻辑

this.router.navigate(["/stations"], {
  queryParams: {
    lat: lat,
    lng: long
  }
})

第二步:修改stations.component.ts接收参数

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-stations',
  templateUrl: './stations.component.html'
})
export class StationsComponent implements OnInit {
  lat?: number;
  lng?: number;

  constructor(private route: ActivatedRoute) {}

  ngOnInit(): void {
    this.route.queryParams.subscribe(params => {
      this.lat = Number(params['lat']);
      this.lng = Number(params['lng']);
      // 后续逻辑处理
    })
  }
}

内容的提问来源于stack exchange,提问作者Hammy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 23:15:11