Ionic version: 6.10.1, Angular version: 10.0.0
Idea
When the app is launched, depending on whether a user is signed in or not, they are navigated to different components. For example, if the user is not logged in, user is taken to IntroPage and the session details are stored using Ionic Storage. From the next time, if the user is logged in, they are being taken to another page called Landing Page.
In my app component after, the device is ready with the plugins loaded, I am calling a method setRootPage()
, which depending upon whether the user session information is stored navigated to different components. But the problem is, the app is navigating to corresponding components before the device ready event is fired.
Any help would be appreciated.
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);
})
}
}
app-routing.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 {}