2

Ive created 2 route guards... one which checks if the user is logged in and one if they are unauthenticated

When the app starts, very briefly it determines, while looking for the localstorage cookie, that the user doest exist and so shows the unauth page (i.e login page)

Im wondering what is the best approach to solve this - in my eyes the authguard with observale to see if the user is logged in or not was the best approach but there is that split second while the code runs that it cannot determine and it wants to show something.

Anyone have any similar issues/creative solutions to solve it.

Kravitz
  • 2,769
  • 6
  • 26
  • 53
  • 1
    Would you mind creating a Github repo with an example that we can test? The guard shouldn't be allowing Angular to load the route so there must be something else happening in the code I guess... – sebaferreras Jun 21 '19 at 12:59
  • Side note: Are you aware that the last version of AngularFire2 [now ships with an auth guard](https://github.com/angular/angularfire2/blob/master/docs/auth/router-guards.md)? – rtpHarry Jun 23 '19 at 08:04

1 Answers1

2

I had this same issue a few months ago, and I solved it by creating an Auth Guard and returning a promise...

auth.guard.ts

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot,
  ): Observable<boolean> | Promise<boolean> | boolean {
    return new Promise(resolve => {
      const userAuthObs = this.afAuth.user.subscribe(user => {
        if (user) {
          resolve(true);
        } else {
          this.router.navigate(['signup']);
          resolve(false);
        }
      });
    });
  }

The app just continues to load normally while it waits for this promise to decide where to direct the user.

You can watch a great video about creating auth guards here... https://www.youtube.com/watch?v=RxLI9_ub6PM

nachshon f
  • 3,540
  • 7
  • 35
  • 67