My project is in IONIC 5 and Firstore. There are 2 different ion-router-outlet
for authenticated (Home) and unauthenticated (Index) routes. Following is the code for dynamically opening the login/home page for users in class app.component.ts
.
this.afAuth.authState.subscribe(user => {
if (user) {
this.router.navigateByUrl('home');
} else {
this.router.navigateByUrl('index');
}
});
Flow: Login Page -> (login) -> Home Page -> (logout) -> Login Page. When the Home page is open the Login page is still loaded and in the navigation stack. The ngOnDestroy
of the Login page does not execute. After the logout, the Login page opens again but the class constructor
and ngOnInit
method does not execute. This is causing a lot of issues as the page initialization is not reloading. The same issue happening for flow Home Page -> (logout) -> Login Page -> (login) -> Home Page.
How can I destroy the Login page after login and Home page after logout so that those can reload if reopened in the same session?
EDIT:
Following is the routing config:
app-routing.module.ts
const routes: Routes = [
{
path: 'home',
canLoad: [AuthGuard],
loadChildren: () => import('./home/home.module').then(m => m.HomePageModule)
},
{
path: 'index',
loadChildren: () => import('./index/index.module').then(m => m.IndexPageModule)
},
];
Both the Home.html
and Index.html
has the same following code.
<ion-content>
<ion-router-outlet></ion-router-outlet>
</ion-content>
index-routing.module.ts
const routes: Routes = [
{
path: '',
component: IndexPage,
children:[
{
path: '',
loadChildren: () => import('../pages/login/login.module').then( m => m.LoginPageModule)
},
]
}
];
home-routing.module.ts
const routes: Routes = [
{
path: '',
component: HomePage,
children:[
{
path: '',
loadChildren: () => import('../pages/user/user.module').then( m => m.UserPageModule)
},
.....
Other authenticated pages
]
Easiest solution that would work, you should navigate to the route with "replaceUrl" NavigationExtras
this.router.navigate(['/home'], { replaceUrl: true });
This replaces the current state in the history, and therefore your Login page will be destroyed. Basically it sets a new root.