首页 > 解决方案 > Ionic 中的奇怪路由行为

问题描述

离子版本:6.10.1角度版本:10.0.0

主意

当应用程序启动时,根据用户是否登录,他们被导航到不同的组件。例如,如果用户未登录,用户将被带到 IntroPage,并且会话详细信息使用 Ionic Storage 存储。从下一次开始,如果用户登录,他们将被带到另一个称为登陆页面的页面。

在我的应用程序组件之后,设备已准备好加载插件,我正在调用一个方法setRootPage(),该方法取决于用户会话信息是否存储导航到不同的组件。但问题是,在触发设备就绪事件之前,应用程序正在导航到相应的组件。

任何帮助,将不胜感激。

app.component.ts

import { Component, OnInit } from '@angular/core';

import { Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { Router } from '@angular/router';

import { AppService } from './services/app.service';
import { StorageService } from './services/storage.service';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})
export class AppComponent implements OnInit {
  
  constructor(private appService: AppService,
    private platform: Platform, private router: Router,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar, private storageService: StorageService
  ) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();

      //Once the device is ready, navigate to a page
      this.setRootPage();
    });
  }

  ngOnInit() {
  }

  setRootPage(){
    this.storageService.getStorageValue('session')
    .then((data) => {
       
      //If logged in navigate to LandingPage
      if(data){
        this.appService.setSessionDetails(data)
        .then((data) => {
          this.router.navigate(['/landing']);        
        });
      }
      //else navigate to IntroPagecorre
      else{
          this.router.navigate(['/intro']);
      }
    }, (err) => {
      console.error("Error occured while getting session data ", err);
    })
  }
}

应用程序路由.module.ts

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  {
    path: 'intro',
    loadChildren: () => import('./pages/intro/intro.module').then( m => m.IntroPageModule)
  },
  {
    path: 'landing',
    loadChildren: () => import('./pages/landing/landing.module').then( m => m.LandingPageModule)
  }
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule {}

标签: angularionic-framework

解决方案


推荐阅读