从google.maps.event.listener

时间:2017-03-17 14:17:09

标签: angular typescript ionic-framework ionic2 ionic3

我的Ionic2项目中用于打印页面的打字稿的组件具有以下结构:

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());

        });
    }
}

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

1 个答案:

答案 0 :(得分:7)

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

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

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