In my ionic 4 app, I store user information natively. The goal is to direct users to the Home Page if their information is already stored when they open the app. If not, they should be routed to the Login Page - pretty standard procedure.
However, the issue I'm facing is a brief display of the Login Page for about 500ms before redirecting to the correct page after reading the information. This inconsistency is not ideal.
I wish for the application to hold off on directing users to the Login Page or Home Page until it receives a response from the storage.
App.component.ts
public initializeApp(): void {
this.platform.ready().then((): void => {
this.statusBar.styleDefault();
this.splashScreen.hide();
this.authService.authState.subscribe((state: boolean): void => {
if (state) {
this.router.navigate(['home']);
} else {
this.router.navigate(['login-register']);
}
});
this.permissionService.requestCameraPermission();
});
}
AuthService.service.ts
public readonly authState: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false)
private _ifLoggedIn(): void {
// check if user info is saved, indicating logged in state
this.userService.getUserInfo().then((response: UserData): void => {
if (response) {
this.authState.next(true);
}
});
}
public isAuthenticated(): boolean {
return this.authState.value;
}
AuthGuard
export class AuthGuardService {
private authService: AuthService;
public constructor(authService: AuthService) {
this.authService = authService;
}
public canActivate(): boolean {
return this.authService.isAuthenticated();
}
}
app-routing.module.ts
const routes: Routes = [
{
path: '',
redirectTo: 'login-register',
pathMatch: 'full',
},
{
path: 'login-register',
loadChildren: () => import('../pages/login-register/login-register.module').then(m => m.LoginRegisterPageModule),
},
{
path: 'home',
loadChildren: () => import('../pages/home/home.module').then(m => m.HomePageModule),
canActivate: [AuthGuardService],
},
];
If you require any additional information, feel free to ask. Thank you!