Ionic 4 Skip Start-Page when user is logged in

I have solved my problems! Now the app starts and when the user is already logged in my dashboard-page will be shown without the Login-page being shown for less than 1 sec.

my app-routing.module

  { path: '', redirectTo: 'menu/tabs/dashboard', pathMatch: 'full' },
  { path: 'login', loadChildren: './pages/login/loginPage.module#LoginPageModule' },
  { path: 'menu', canActivate: [AuthGuard], loadChildren: './pages/menu/menu.module#MenuPageModule' },

my app.component.ts

 //Check if user is logged-in; if so the dashboard will be loaded otherwise the login-page
            this.authenticationService.authenticationState.subscribe(state => {
                if (state) {
                    console.log("user is logged in");
                    this.navController.navigateRoot(['menu/tabs/dashboard']);
                    this.splashScreen.hide();
                } else {
                    console.log("user is NOT logged in");
                    this.navController.navigateRoot('login');
                    this.splashScreen.hide();
                }
            });

my authenticationService.service.ts

export class AuthenticationService {

  authenticationState = new BehaviorSubject(false);

  constructor(private storage: Storage,
              private platform: Platform,
              public global: GlobalProvider) {
    this.platform.ready().then(async () => {
      this.checkToken();
    });
  }

  checkToken() {
    if (this.global.getUserData() || this.global.getUserData() !== null){
      this.authenticationState.next(true);
    }
  }

  login() {
      this.authenticationState.next(true);
  }

  logout() {
      localStorage.clear();
      this.authenticationState.next(false);
  }

  isAuthenticated() {
    return this.authenticationState.value;
  }

}

my auth.guard.ts

export class AuthGuard implements CanActivate {

    constructor(public authenticationService: AuthenticationService) {
    }

    canActivate(): boolean {
        return this.authenticationService.isAuthenticated();
    }

}

When the user is being logged in i set some data into the localstorage. In my authService i look for these data and set the state to true or false. In the app.component.ts i subscribe to this state and switch the root navigation.

4 Likes