从google.maps.event.listener调用我的函数

pit*_*zzo 3 typescript ionic-framework ionic2 ionic3 angular

我在Ionic2项目中以页面的typescript编写的组件具有以下结构:

import { Component, ViewChild, ElementRef } from '@angular/core';
...
declare var google;

@Component({
    selector: 'page-search',
    templateUrl: 'search.html'
})

export class SearchPage {
    @ViewChild('map') mapElement: ElementRef;
    map: any;
    guideList: Array<Guide>;
    text: any;
    lat : any; 
    lon : any;

    constructor(public navCtrl: NavController, public recoshService: Recosh, public alertCtrl: AlertController) {
        ...
    }

    ngOnInit(){ 
        this.loadMap();
    }

    loadGuides() {
        ...
    }

    setLat(l){
        this.recoshService.setLat(l);
        this.lat = l;
    }

    setLon(l){
        this.recoshService.setLon(l);
        this.lon = l;
    }

    setPos(lat, lon){
        this.setLon(lon);
        this.setLat(lat);
        this.loadGuides();
    }

    loadMap(){
        ...

        let marker = new google.maps.Marker({
            position: this.map.getCenter(),
            icon: {
                path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,
                scale: 5,
                strokeWeight:2,
                strokeColor:"#B40404"
            },
            draggable:true,
            map: this.map,
        });

        google.maps.event.addListener(marker, 'dragend', function() {

            this.setPos(marker.getPosition().lat(),marker.getPosition().lng());

        });
    }
}
Run Code Online (Sandbox Code Playgroud)

但在google.maps.event.addListener(){..}我内心无法达到setPos()SearchPage班上宣布的内容.考虑到我的结构,我该如何调用此函数?

seb*_*ras 8

你需要使用这样的箭头函数:

google.maps.event.addListener(marker, 'dragend', () => {
    this.setPos(marker.getPosition().lat(),marker.getPosition().lng());
});
Run Code Online (Sandbox Code Playgroud)

通过使用箭头函数,该this属性不会被覆盖,仍然引用组件实例.