Login/Home 在 Ionic 5 路由器中 login/logout 时页面未被破坏

Login/Home pages not destroyed when login/logout in Ionic 5 router

我的项目在 IONIC 5 和 Firstore 中。有 2 种不同的 ion-router-outlet 用于经过身份验证的(主页)和未经身份验证的(索引)路由。以下是为 class app.component.ts.

中的用户动态打开 login/home 页面的代码
  this.afAuth.authState.subscribe(user => {
    if (user) {
      this.router.navigateByUrl('home');
    } else {
      this.router.navigateByUrl('index');
    }
  }); 

流程:登录页面->(登录)->主页->(注销)->登录页面。当主页打开时,登录页面仍处于加载状态并位于导航堆栈中。登录页面的ngOnDestroy不执行。注销后,登录页面再次打开,但 class constructorngOnInit 方法不执行。这导致了很多问题,因为页面初始化没有重新加载。流主页 ->(注销)-> 登录页面 ->(登录)-> 主页也会发生同样的问题。 如何销毁登录后的登录页面和注销后的主页,以便在同一会话中重新打开时重新加载这些页面?

编辑:

路由配置如下:

应用-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)
  },
];

Home.htmlIndex.html都具有相同的以下代码。

<ion-content>
  <ion-router-outlet></ion-router-outlet>
</ion-content>

索引-routing.module.ts

const routes: Routes = [
  {
    path: '',
    component: IndexPage,
    children:[
      {
        path: '',
        loadChildren: () => import('../pages/login/login.module').then( m => m.LoginPageModule)
      },
    ]
  }
];

首页-routing.module.ts

const routes: Routes = [
  {
    path: '',
    component: HomePage,
    children:[
      {
        path: '',
        loadChildren: () => import('../pages/user/user.module').then( m => m.UserPageModule)
      },
.....
Other authenticated pages
]

您描述的看似意外的行为是由于 Ionic。更具体地说,是由于 how Ionic deals with the life of a page.

When you navigate to a new page, Ionic will keep the old page in the existing DOM, but hide it from your view and transition the new page.

...

Because of this special handling, the ngOnInit and ngOnDestroy methods might not fire when you would usually think they should.

ngOnInit will only fire each time the page is freshly created, but not when navigated back to the page. For instance, navigating between each page in a tabs interface will only call each page's ngOnInit method once, but not on subsequent visits. ngOnDestroy will only fire when a page "popped".

在不太了解您的应用程序的情况下,我建议您对页面组件使用 Ionic Lifecycle events 而不是 Angular。听起来您可能只需将 ngOnInit 替换为 ionViewWillEnter 并将 ngOnDestroy 替换为 ionViewWillLeaveionViewDidLeave.

文档的下方是一些有用的内容 guidance for each lifecycle method

最简单的解决方案,您应该使用 "replaceUrl" NavigationExtras

导航到路线

this.router.navigate(['/home'], { replaceUrl: true });

这将替换历史记录中的当前状态,因此您的登录页面将被销毁。基本上它设置了一个新的根。

Reference

我认为您遇到了破坏上一页的问题。 在 Iconic 中,当您导航到其他页面时,它仍然保持 DOM 中的前一个页面。

所以你的 ngOnDestroy() 没有被调用。

您可以将 navigate() 函数替换为 navigateRoot()。这将解决您的问题并且会被彻底摧毁。

所以你的代码行应该有点像:

 this.afAuth.authState.subscribe(user => {
  if (user) {
    this.router.navigateRoot('home');
  } else {
    this.router.navigateRoot('index');
  }
 }); 

希望这能解决您的问题。