首页 > 解决方案 > 在 Ionic 5 路由器中登录/注销时登录/主页不会被破坏

问题描述

我的项目在 IONIC 5 和 Firstore 中。经过身份验证的 (Home) 和未经身份验证的 (Index) 路由有 2 种不同ion-router-outlet。以下是为 class 中的用户动态打开登录/主页的代码app.component.ts

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

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

编辑:

以下是路由配置:

应用程序路由.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
]

标签: angularionic-frameworkroutesangular-routingionic5

解决方案


最简单的解决方案,您应该使用“replaceUrl”NavigationExtras 导航到路线

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

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

参考


推荐阅读