简体   繁体   English

Angular 2 - 通过class属性在视图中显示事件侦听器函数的值

[英]Angular 2 - display value from an event listener function in the view via class property

I'm working with ionic 2/angular 2 and google maps. 我正在使用离子2 /角度2和谷歌地图。

i have a class 我上课了

    import {Page, Platform} from  'ionic-angular';
    import {Geolocation} from 'ionic-native';
    import {Http, Response} from '@angular/http';

    @Page({
        templateUrl: 'build/pages/mapPage/mapPage.html',
    })

    export class MapPage {

        date: String = new Date().toISOString();
        address: any = 'Pick a place';

        constructor(private platform: Platform, private http: Http) {
            this.platform = platform;
            this.initializeMap();
        }


        initializeMap() {
        let HTTPP = this.http;
        this.platform.ready().then(() => {
            var myLatLng = {};
            var image = 'custom/img/map-marker-small.png';

            Geolocation.getCurrentPosition().then(pos => {
                myLatLng = { lat: pos.coords.latitude, lng: pos.coords.longitude };                 
            })
                .then(() => {
                    var minZoomLevel = 17;

                    var map = new google.maps.Map(document.getElementById('map_canvas'), {
                        zoom: minZoomLevel,
                        center: myLatLng,
                        mapTypeId: google.maps.MapTypeId.ROADMAP
                    });
                });

             var getAddress = function (lat, lng) {
                    let mapUrl = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + lng + '&key=XXXXXXXXX';  // URL to web API
                    let address = "";

                    return HTTPP.get(mapUrl)
                        .toPromise()
                        .then(data => {
                            let data2 = data.json().results;                                
                            data2[0]['address_components'].forEach(add => {
                                address += add.long_name + ", ";
                            });
                            return address;
                        });
                }

                marker.addListener('dragend', function (event) {
                    var lat = event.latLng.lat();
                    var lng = event.latLng.lng();

                    console.log("lat: " + lat + ", lng: " + lng);

                    getAddress(lat, lng)
                    .then(function(address){
                        console.log(address); //WORKS CORRECTLY
                        //but can't access `this` here. 
                        //this.address = address //THIS IS WHAT I WANT 
                        return address;
                    })

                });
           });
         }
      }

What i want to accomplish is to get the address of the marker that has been dragged to a coordinate and display it to the user in the front end 我想要完成的是获取已拖动到坐标的标记的地址并将其显示给前端的用户

 <ion-navbar *navbar>
  <ion-title>
    Map Example
  </ion-title>
</ion-navbar>

<ion-content class="home">
  <div id="map_canvas" style="height: 60%"></div>
  <ion-item>
    <ion-label>Date</ion-label>
    <ion-datetime displayFormat="DDD MMM DD, h:mm A" pickerFormat="DDD DD MMM h mm A" [(ngModel)]="date"></ion-datetime>

  </ion-item>
  <ion-item>
   {{address}}
  </ion-item>
</ion-content>

When the marker is dragged i have successfully gotten the coordinates and have successfully gotten the address string. 拖动标记后,我已成功获取坐标并成功获取地址字符串。 But the this operator is not available in the event listener function for the dragend event of the marker. 但是this运算符在标记的dragend事件的事件监听器函数中不可用。

How can i equate this.address to my address that i got inside the event listener? 我如何将this.address等同于我在事件监听器中的地址?

I have tried to make a general refrence to this by doing let self = this; 我试图通过let self = this;this做出一般性的反思let self = this; and then using self.address = address inside the function in hopes that it would reflect in the view. 然后在函数内使用self.address = address ,希望它能反映在视图中。 but it didn't work. 但它不起作用。

All i want to do is to display the address in the front end when the user drags the marker to a new location. 我想要做的就是当用户将标记拖动到新位置时在前端显示地址。

Any help would be appreciated thanks!! 任何帮助将不胜感激!!

Change 更改

function (event) {

to

(event) => {

to retain the scope of this 保留的范围this

See also https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions 另请参见https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions

There are two places where you lose context: dragend event handler and then callback function. 丢失上下文有两个地方: dragend事件处理程序, then回调函数。 Use arrow function for both of them, this will preserve lexical scope: 对它们使用箭头函数,这将保留词法范围:

marker.addListener('dragend', event => {

  var lat = event.latLng.lat();
  var lng = event.latLng.lng();

  getAddress(lat, lng)
    .then(address => this.address = address);

}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM