【问题标题】:Calling a method from the constructor in Angular2/IONIC2从 Angular2/IONIC2 中的构造函数调用方法
【发布时间】:2016-12-09 21:20:31
【问题描述】:

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

例如,我想从构造函数中调用 getPosition 方法,但抛出一个异常“getPosition is not a function”。

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;    
  }

}

【问题讨论】:

  • 左右括号不匹配
  • 我修好了。谢谢:)

标签: javascript angular typescript ionic2


【解决方案1】:

改变,

// 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 而不是()=&gt;(粗箭头语法),因此您的this 是在.addEventListener 部分中引用您的函数对象

【讨论】:

    猜你喜欢
    • 2013-08-10
    • 2013-05-08
    • 2011-10-22
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    • 2015-10-01
    • 2016-02-05
    • 1970-01-01
    相关资源
    最近更新 更多