从Angular2 / IONIC2中的构造函数调用方法

时间:2016-12-09 21:20:31

标签: javascript angular typescript ionic2

我是Angular 2的新手,我想知道是否可以从当前构造函数中调用子方法。

例如,我想从构造函数中调用 getPosition 方法,但抛出一个“ getPosition不是函数”的异常。

import { Component } from '@angular/core';
import { NavController, AlertController } from 'ionic-angular';
import { Platform } from 'ionic-angular';
import { Q } from 'q';

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

export class HomePage {

  private map;

  constructor(public navCtrl: NavController, platform: Platform, public alertCtrl: AlertController) {    
    platform.ready().then(() => { 
      try {
        let div = document.getElementById("map_canvas");
        // Initialize the map view
        this.map = (<any>window).plugin.google.maps.Map.getMap(div);

        // Wait until the map is ready status.        
        this.map.addEventListener((<any>window).plugin.google.maps.event.MAP_READY, function() {
          this.getPosition().then(data => {
            let GOOGLE = new (<any>window).plugin.google.maps.LatLng(data.latitude, data.longitude);
            this.map.setCenter(GOOGLE);
          }).catch(err => {            
            alert(err);
          });
        });
      } catch(err) {
        alert(err);
      }     
    }).catch(err => {
      alert(err);
    });
  }


  getPosition() {
    let deferred = Q.defer();
    try {
      this.map.getMyLocation(location => {
        deferred.resolve( {
          latitude: location.latLng.lat,
          longitude: location.latLng.lng
        });
      }, err => {
        deferred.reject(err);              
      });

    } catch(err) {
      deferred.rejec(err);
    }
    return deferred.promise;    
  }

}

1 个答案:

答案 0 :(得分:3)

更改,

// Wait until the map is ready status.
this.map.addEventListener((<any>window).plugin.google.maps.event.MAP_READY, function() {
      this.getPosition().then(data => {
        let GOOGLE = new (<any>window).plugin.google.maps.LatLng(data.latitude, data.longitude);
        this.map.setCenter(GOOGLE);
      }).catch(err => {            
        alert(err);
      });
    });

// Wait until the map is ready status.
this.map.addEventListener((<any>window).plugin.google.maps.event.MAP_READY, ()=> {
          this.getPosition().then(data => {
            let GOOGLE = new (<any>window).plugin.google.maps.LatLng(data.latitude, data.longitude);
            this.map.setCenter(GOOGLE);
          }).catch(err => {            
            alert(err);
          });
        });

由于您使用的是function而不是()=>(胖箭头语法),因此this正在引用.addEventListener部分内的函数对象