在 Ionic 5 路由器中登录/注销时登录/主页不会被破坏

Tap*_*jee 7 routes angular-routing ionic-framework angular ionic5

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

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

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

编辑:

以下是路由配置:

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)
  },
];
Run Code Online (Sandbox Code Playgroud)

无论是Home.htmlIndex.html具有相同下面的代码。

<ion-content>
  <ion-router-outlet></ion-router-outlet>
</ion-content>
Run Code Online (Sandbox Code Playgroud)

index-routing.module.ts

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

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
]
Run Code Online (Sandbox Code Playgroud)

Che*_*sal 8

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

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

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

参考