Gene Gene - 6 months ago 62
Javascript Question

Ionic 2: Unable to navigate from inner function

I'm trying to navigate to a page , upon clicking on a google map marker. I'm able to do it outside the inner function (Inside initializeMap function only), just having problems doing it in a inner function.

This is my constructor:

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


Inside my initializeMap method contains the populateLocks method:

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


Using this.navController or navController throws me error like:

for this.navController.push

enter image description here

for navController.push

enter image description here

Answer

Either use () => instead of function ()

More information: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions

or use var self = this; outside the function and refer to self.navController instead of this.navController like so:

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