繁体   English   中英

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

[英]Calling a method from the constructor in Angular2/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;    
  }

}

更改,

// 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部分内的函数对象

暂无
暂无

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

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