离子2:无法从内部功能导航

时间:2016-05-09 02:59:07

标签: javascript ionic-framework angular ionic2

点击谷歌地图标记时,我正试图导航到某个页面。我能够在内部函数之外执行它(仅在initializeMap函数内部),只是在内部函数中执行它时遇到了问题。

这是我的构造函数:

static get parameters() {
    return [[NavController],[Platform]];
  }

  constructor(navController, platform, app) {
    this.navController = navController;
    this.platform = platform;
    this.app = app;

    this.map = null;
    this.markers = [];

   platform.ready().then(() => {
    this.initializeMap();
   });
  }

我的initializeMap方法里面包含populateLocks方法:

function populateLocks(auth,unauth,map){

for (var k in auth) {
    (function (id) {
       var auth = new google.maps.Marker({
            icon: authImage,
             map: map,
             position: authLocks[id].latLng
        });
       google.maps.event.addListener(auth, 'click', function () {
         //alert(auth[id].id);
         this.navController.push(SettingsPage);
          });
     })
     (k)
  }

使用this.navController或navController会抛出错误,如:

for this.navController.push

enter image description here

用于navController.push

enter image description here

1 个答案:

答案 0 :(得分:2)

使用() =>代替function ()

更多信息:https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions

或在函数外部使用var self = this;并参考self.navController代替this.navController,如下所示:

var self = this;
google.maps.event.addListener(auth, 'click', function () {
   //alert(auth[id].id);
   self.navController.push(SettingsPage);
});