[Ionic2] how to access outside method


#1

Hello. I can’t resolve how to access NavController from closure.
this code have “EXCEPTION: TypeError: Cannot read property ‘push’ of undefined”.
Please how to write.

thanks.

login(){
    this.fb.login().then(
        function(data) {
            if (data.status === 'connected') {
                this.nav.push(Signup,{},{});
            }else{
                console.log('not Logged in.');
            }
        });
}

#2

Use this syntax instead:

login(){
	this.fb.login().then((data) => {
		if (data.status === 'connected'){
			this.nav.push(Signup);
		} else {
			console.log('not Logged in.');
		}
	});
}

#3

thanks!!
It gone well!!!


#4

Just to clarify the reasoning for those who may come across this issue.

The problem is JavaScripts scoping of the ‘this’ object.

In the OPs code, function() causes ‘this’ to scope itself to the anonymous function.

ES6 new arrow functions give the expected scope where ‘this’ refers to the calling object.


#5

thanks. I learned a lot from that!