I am using ionic-angular:3.9.2 and I really struggle to understand the logic behind the lifecycle events in combination with protecting pages, even though I digged into the Ionic sources on github.
I have a protected page, which is displayed in Tabs. Whenever an unauthorized user tries to access that page, I’d like to redirect him (on the root controller) to the login page. If he navigates back using the back button in the header, the first tab is selected on ionViewDidEnter and the home screen is displayed to the user. Needs more custom code than expected, but so far so good.
However, if the user navigates to the protected page another time ionViewCanEnter is not triggered anymore. I expected the page to be destroyed, since it is not on any stack, but this does not happen. I guess that’s the reason why ionViewCanEnter is not triggered again.
This is how my page looks like:
@IonicPage({
name: 'MyProtectedPage'
})
@Component({
selector: 'my-protected-page',
templateUrl: 'protected.page.html'
})
export class MyProtectedPage implements OnInit, OnDestroy {
constructor(private navCtrl: NavController) {
console.log('page constructor');
}
ionViewCanEnter() {
console.log('can enter');
// push the login page on the root controller, so that login page is displayed without the tab bar
this.navCtrl.parent.parent.push(LOGIN_PAGE_NAME);
return false;
}
ionViewWillLeave() {
console.log('will leave');
}
ngOnDestroy(): void {
console.log('page destroy');
}
ngOnInit(): void {
console.log('page init');
}
}
The view stacks look like this:
- User opens app:
n4: [TabsPage]
--tabs, selected: 0
---- t0-0: [HomePage]
---- t0-1: []
---- t0-2: []
---- t0-3: []
- user is redirected to login
n4: [TabsPage, LoginPage]
--tabs, selected: 2
---- t0-0: [HomePage]
---- t0-1: []
---- t0-2: []
---- t0-3: []
- user clicks on the back button
n4: [TabsPage]
--tabs, selected: 0
---- t0-0: [HomePage]
---- t0-1: []
---- t0-2: []
---- t0-3: []
I cannot really use ionViewCanEnter due to various reasons.
Am I misunderstanding something?
If I pop a page explicitly, the IonicPage gets destroyed, but if it never becomes member of any stack I have no way to kill it? Not even manually?