Ionic 4 can't skip login page when app starts or reloads

I have built jwt authentication system in my ionic 4 app. If the token is available user will be redirected to the " menu/items " page else redirected to " home " page which performs login.

I have set the default path to " menu/items " page. But when the app starts or reloads " home " page is displayed for a second and then redirected to " menu/items " page even though default path is " menu/items ".

I can’t get why this is happening.

Thank you in advance

here is my code

app-routing.module.ts

const routes: Routes = [
  { path: '', redirectTo: 'menu/items', pathMatch: 'full' },
  { path: 'home', loadChildren: () => import('./pages/home/home.module').then(m => m.HomePageModule) },

  { path: 'details', loadChildren: () => import('./pages/details/details.module').then(m => m.DetailsPageModule) },
  { path: 'user-type', loadChildren: () => import('./pages/user-type/user-type.module').then(m => m.UserTypePageModule) },

  { path: 'menu', canActivate: [AuthGuard], loadChildren: () => import('./pages/menu/menu.module').then(m => m.MenuPageModule) },

];

authentication.service.ts

authenticationState = new BehaviorSubject(false);

  constructor(private storage: StorageService, private plt: Platform, private router: Router) {

    this.plt.ready().then(() => {
      this.checkToken();
    });
   }

   checkToken() {
    this.storage.get(TOKEN_KEY).then(res => {
      if (res) {
        this.authenticationState.next(true);
      }
    })
  }

  login() {
    return this.storage.set(TOKEN_KEY, 'Bearer 1234567').then(() => {
      this.authenticationState.next(true);
    });
  }

  logout() {
    return this.storage.clear().then(() => {
      this.authenticationState.next(false);
      this.router.navigate(['home'])

    });
  }

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

auth.guard.ts

constructor(public auth: AuthenticationService) {}

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

Hey,

here is what i do:

  • Don’t set a Default Page
  • On Startup check Auth Status and navigate
  • After Navigation: Hide Splash Screen
1 Like

@EinfachHans But still user is redirected to the login page for a second and then go to the main page. Why this is happening? As your answer, I didn’t set default page. So why it always redirects to the login page?
And how to solve this?
Thank you

Can’t be. Can you provide your routing Files?