簡體   English   中英

在 Ionic 5 路由器中登錄/注銷時登錄/主頁不會被破壞

[英]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 constructorngOnInit方法不執行。 這會導致很多問題,因為頁面初始化沒有重新加載。 流程主頁->(注銷)->登錄頁面->(登錄)->主頁發生了同樣的問題。 如何在登錄后銷毀登錄頁面和注銷后的主頁,以便在同一個 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.htmlIndex.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替換為ionViewWillLeaveionViewDidLeave

文檔的下方是每個生命周期方法的一些有用的指導

我認為您正面臨破壞前一頁的問題。 在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM