[英]Login/Home pages not destroyed when login/logout in Ionic 5 router
我的项目在 IONIC 5 和 Firstore 中。 有 2 种不同ion-router-outlet
用于经过身份验证的 (Home) 和未经身份验证的 (Index) 路由。 以下是在 class app.component.ts
中为用户动态打开登录/主页的代码。
this.afAuth.authState.subscribe(user => {
if (user) {
this.router.navigateByUrl('home');
} else {
this.router.navigateByUrl('index');
}
});
流程:登录页面->(登录)->主页->(注销)->登录页面。 当主页打开时,登录页面仍然加载并在导航堆栈中。 登录页面的ngOnDestroy
不执行。 注销后,登录页面再次打开,但 class constructor
和ngOnInit
方法不执行。 这会导致很多问题,因为页面初始化没有重新加载。 流程主页->(注销)->登录页面->(登录)->主页发生了同样的问题。 如何在登录后销毁登录页面和注销后的主页,以便在同一个 session 中重新打开时可以重新加载?
编辑:
以下是路由配置:
应用程序路由.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)
},
];
Home.html
和Index.html
具有相同的以下代码。
<ion-content>
<ion-router-outlet></ion-router-outlet>
</ion-content>
索引路由.module.ts
const routes: Routes = [
{
path: '',
component: IndexPage,
children:[
{
path: '',
loadChildren: () => import('../pages/login/login.module').then( m => m.LoginPageModule)
},
]
}
];
家庭路由.module.ts
const routes: Routes = [
{
path: '',
component: HomePage,
children:[
{
path: '',
loadChildren: () => import('../pages/user/user.module').then( m => m.UserPageModule)
},
.....
Other authenticated pages
]
最简单的解决方案,您应该使用“replaceUrl”NavigationExtras 导航到路线
this.router.navigate(['/home'], { replaceUrl: true });
这将替换历史记录中当前的 state,因此您的登录页面将被销毁。 基本上它设置了一个新的根。
您描述的看似意外的行为是由于 Ionic 造成的。 更具体地说,这是由于Ionic 如何处理页面的生命周期。
当您导航到新页面时,Ionic 会将旧页面保留在现有 DOM 中,但将其隐藏在您的视图中并转换新页面。
...
由于这种特殊处理,ngOnInit 和 ngOnDestroy 方法可能不会在您通常认为应该触发的时候触发。
ngOnInit 只会在每次新创建页面时触发,但不会在导航回页面时触发。 例如,在选项卡界面中的每个页面之间导航只会调用每个页面的 ngOnInit 方法一次,而不会在后续访问时调用。 ngOnDestroy 只会在页面“弹出”时触发。
在不了解您的应用程序的情况下,我建议您对页面组件使用Ionic Lifecycle 事件而不是 Angular 事件。 听起来您可能只需将ngOnInit
替换为ionViewWillEnter
并将ngOnDestroy
替换为ionViewWillLeave
或ionViewDidLeave
。
文档的下方是每个生命周期方法的一些有用的指导
我认为您正面临破坏前一页的问题。 在 Iconic 中,当您导航到另一个页面时,它仍然保留 DOM 中的前一个页面。
所以你的 ngOnDestroy() 没有被调用。
您可以将您的navigate() function 替换为navigateRoot() 。 这将解决您的问题,并会完全被破坏。
所以你的代码行应该有点像:
this.afAuth.authState.subscribe(user => {
if (user) {
this.router.navigateRoot('home');
} else {
this.router.navigateRoot('index');
}
});
我希望这能解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.