首页 > 解决方案 > 如何使用 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,则地图应在该中心点初始化。

标签: angularangular2-routingangular-routingangular8angular-router

解决方案


我可以通过订阅ActivatedRoute 的queryParams 来完成这项工作。

 this.route.queryParams.subscribe(params => {
            this.lat = params.lat;
            this.lon = params.lon;
        });

推荐阅读