Reputation: 487
This is my Function:
checkStack(){
let canGoBack = this.navCtrl.canGoBack()
console.log('canGoBack: ',canGoBack);
if(canGoBack === true){
console.log('Not RootPage.');
} else {
let alert = this.alertCtrl.create({
title: 'Exit',
message: 'sure?',
buttons: [
{
text: 'Yes',
role: 'cancel',
handler: () => {
console.log('Cancel clicked');
}
},
{
text: 'No',
handler: () => {
this.platform.exitApp();
}
}
]
});
alert.present();
}
}
i am call in IonViewDidLoad():
this.platform.registerBackButtonAction(this.checkStack);
But if i click the BackButton it fails with Message:
"Uncaught TypeError: Cannot read property 'canGoBack' of undefined"
Whats wrong?
Upvotes: 2
Views: 3435
Reputation: 65
I had the same issue, and all I needed to solve it was to remove the parenthesis.
Instead of:
this.navCtrl.canGoBack()
Use:
this.navCtrl.canGoBack
Upvotes: -1
Reputation: 487
Here is my Solution:
constructor(public platform: Platform, public app: App){
initializeApp()
}
this.platform.registerBackButtonAction(() => {
let activeNav = this.app.getActiveNav();
if(activeNav.canGoBack()){
// not Root
} else {
// is Root
}
I am defined this in:
initializeApp(){
this.platform.ready().then(() => {...})
}
and call in Constructor. Works very well ;-)
Upvotes: 4
Reputation: 333
The error you receive indicates that your navCtrl variable is undefined. Make sure you instantiate it in the constructor of your page. Like this:
constructor(
public navCtrl:NavController
) {
// constructor logic goes here
}
Note that including public is necessary for the variable to be assigned and available (not be undefined) outside of the constructor method.
Upvotes: 1