angular - 如何使用 ActivateRoute 的 query params map 来启动导航图,反之亦然?
问题描述
以下是我的路由解析器、路由配置和组件。我正在尝试使用 url 参数来初始化地图(想象一下谷歌地图) - 似乎不起作用,因为始终使用默认的纬度/经度值并且从 ActivatedRoute 检索到的参数值为空。
网址:http://localhost:4500?lat=12&lng=14
此外,下一步将更新路线查询参数以反映地图上的任何平移操作(用户拖动地图并且中心坐标发生变化)
export class MyComponent {
lat: number;
lon: number;
private map: any;
constructor(private route: ActivatedRoute, private router: Router) {
this.route.data.subscribe(data => {
this.lat = Number(this.route.snapshot.queryParamMap.get('lat')) || 10;
this.lon = Number(this.route.snapshot.queryParamMap.get('lon')) || 12;
this.updateUrl();
}
updateUrl() {
this.router.navigate([], {
relativeTo: this.route,
queryParams: {
lat: this.lat,
lon: this.lon
},
queryParamsHandling: 'preserve',
// preserve the existing query params in the route
skipLocationChange: false
});
}
public ngOnInit() {
this.map = new GoogleLikeMap()
this.map.setCameraGeolocationAndZoom(
new GeoCoordinates(Number(this.lat), Number(this.lng)),
14
);
this.map.addEventListener('panning', () => {
this.lat = this.map.geoCenter.lat;
this.lng = this.map.geoCenter.longitude;
this.router.navigateByUrl('/?lat=' + this.lat + '&lng=' + this.lng);
});
}
}
尝试以 http:localhost:4500 访问我的 url 如果 URL 中尚不存在,它应该将默认的 lat 和 lng 值附加到 url。如果值已经通过浏览器传递到 url,则地图应在该中心点初始化。
解决方案
我可以通过订阅ActivatedRoute 的queryParams 来完成这项工作。
this.route.queryParams.subscribe(params => {
this.lat = params.lat;
this.lon = params.lon;
});
推荐阅读
- python - 如何在 python 3.8 的另一个函数中调用一个函数?
- python - 将数组值添加到标识符与其他数组匹配的 numpy recarray
- node.js - Vercel Serverless 功能与 nuxtjs ECONNRESET 客户端网络套接字在建立安全 TLS 连接之前断开连接
- android-jetpack-compose - Jetpack Compose 列表差异动画
- reactjs - fullcalendar 使用模态响应添加事件
- python - 将字典转换为具有嵌套值列表的数据框
- php - 我的 SQL/PHP 准备好的语句有问题
- python - 使用 Colab 和 pyngrok 进行 Streamlit - 无法完成隧道连接 - 版本问题?
- python-3.x - 使用 Selenium Python 在 Google 主页上单击 Google 搜索按钮时出现元素不可交互错误
- javascript - Firebase 按文档 ID PLUS 属性值查询