Hello,
I’ve been having issues when starting up my app due do async methods being called inside initializeApp(). Maybe I just don’t know the correct place to to the required startup routines as I didn’t see any other topic with this issue.
When starting up the app I need to hit localstorage to see if there’s already some authentication info saved there, as well as other user configuration options. This is my code, stripped of some out of the scope, synchronous stuff.
constructor(private platform: Platform, private configService: ConfigService, private authService: AuthService, private pushService: NotificationService, private locationService: LocationService, private eventService: Events, private screenOrientation: ScreenOrientation) {
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(async () => {
await this.authService.fillAuthData();
if (this.authService.IsAuthenticated) { //promise that reads and writes using @ionic/storage
await this.configService.getUserConfig(); //promise that reads and writes using @ionic/storage
await this.pushService.getNotificationSettingsFromStorage(); //promise that reads and writes using @ionic/storage
await this.locationService.getLocation(); //promise that makes an http get call for state/city names
this.authService.redirectOnLogin();
}
else if (await this.authService.increaseAppRunCount() == 0) { //promise that reads and writes using @ionic/storage
this.authService.redirectToWelcomePage();
}
if (Capacitor.isPluginAvailable("SplashScreen")) {
SplashScreen.hide();
}
});
}
So, as soon as a Promise returning function is called using await, like authService.fillAuthData()
, the code execution goes back to whoever called the app.component.ts constructor. And everything else starts going on, like the default start route getting navigated to as my route guard breakpoints get hit.
The page for the default route expects the location to be ready. Also expects the authentication info to be there, but it isn’t. The route guard routes back to the login page. Well, you get the picture.
By the time SplashScreen.hide();
is called the splash screen is long gone as, apparently, the router.navigateByUrl()
calls in the route guard make it go await.
All @ionic/storage methods are async and I cant avoid this behavior. What is the best approach here? Where should I do this startup routines on app start?
1 post - 1 participant