Reputation: 1521
I need to close all current modal popups and log out the user in ionic 2 application when the device goes to idle.
I used following methods to close popups in the home component.
this.viewController.dismiss().then(_ => {
console.log("modal dismiss");
}).catch(error => {
console.log(error)
});
and
this.navController.popAll().then(_ => {
console.log("modal dismiss");
}).catch(error => {
console.log(error);
})
But it throws following error You can't remove all pages in the navigation stack. nav.pop() is probably called too many times.
and does not close any popup. Anyone knows how to do it?
Upvotes: 4
Views: 7461
Reputation: 11
Ok so I had the same issue and I solved it this way. The solution is to store all the modal instances using a service in an array. Then use a loop and dismiss all the modals refering them from that array.
modal.html
<ion-button (click)="openModal()"> Open Modal <ion-button>
<ion-button (click)="close()"> Close Modals <ion-button>
modal.service.ts
modalInst=[];
i=0;
storeModal(x)
{
this.modalInst[this.i]=x;
this.i++;
}
modal.ts
openModal()
{
var modal = await this.viewCtrl.create({
component: ModalPage
});
this.service.storeModal(modal);// storing modal instances in an array
return await modal.present();
}
close()
{
for(var i=0; i< this.service.modalInst.length; i++)
{
this.service.modalInst[i].dismiss();
}
}
Upvotes: 1
Reputation: 1766
We can create a recursive function which takes a current active modal reference and dismiss that modal after that we will call on the that function again in dismiss() event. Here is the code ,
recursive function
public dismissAllModal () {
let activeModal = this.ionicApp._modalPortal.getActive();
if (activeModal) {
activeModal.dismiss().then(() => {
this.dismissAllModal()
});
}
}
Call the function where we should remove all modals (I placed in login page in constructor)
this.viewCtrl.dismiss().then(_ => {
this.dismissAllModal()
})
Upvotes: 1
Reputation: 49
This worked for me
constructor(public navCtrl: NavController,public ionicApp: IonicApp){}
this.viewCtrl.dismiss().then(_=>{
let activePortal = this.ionicApp._modalPortal.getActive()
if (activePortal) {
activePortal.dismiss(); //can use another .then here
}
});
Upvotes: 4
Reputation: 5013
viewController.dismiss()
only closes the current Modal. Meaning you will have to keep a reference to all open modals in and call dismiss()
on each one.
You can set use navController.setRoot(LoginPage)
(link) to show the login-page.
Upvotes: 4