title: Using BehaviorSubject in auth-guard's canActivate
body: <p><strong>What I want to achieve:</strong> I want to share authentication state across my application using BehaviorSubject. I use the authentication state e.g. inside an auth-guard to prevent the user from visiting login/register pages when the user already is authenticated. </p>
  
  <p><strong>Problem:</strong> because the BehaviorSubject has a initial value, which is false (not logged in), it seems that the auth-guard takes this first value, instead of waiting for the uid-sync.</p>
  
  <p><em>AuthInfo</em> (Auth state store):</p>
  
  <pre><code>export class AuthInfo {
  
    constructor(public uid: string) {}
  
    isLoggedIn() {
      return !!this.uid;
    }
  }
  </code></pre>
  
  <p><em>AuthService</em>:</p>
  
  <pre><code>@Injectable()
  export class AuthService {
  
    static UNKNOWN_USER = new AuthInfo(null);
    authInfo$: BehaviorSubject&lt;AuthInfo&gt; = new BehaviorSubject&lt;AuthInfo&gt;(AuthService.UNKNOWN_USER);
  
    constructor(private af: AngularFire) {
      this.af.auth.subscribe(auth =&gt; {
        if (auth) {
          console.log('got the uid');
          this.authInfo$.next(new AuthInfo(auth.uid));
        } else {
          this.authInfo$.next(AuthService.UNKNOWN_USER);
        }
      });
    }
  
    logIn(email: string, password: string): Promise&lt;FirebaseAuthState&gt; {
      return this.af.auth.login({email: email, password: password});
    }
  }
  </code></pre>
  
  <p><em>AuthGuard</em>:</p>
  
  <pre><code>@Injectable()
  export class AuthGuard implements CanActivate {
  
    constructor(private authService: AuthService,
                private router: Router) {
    }
  
    canActivate(): Observable&lt;boolean&gt; {
      return this.authService.authInfo$.map(authInfo =&gt; {
        if (authInfo.isLoggedIn()) {
          this.router.navigate(['/user'])
        }
        return !authInfo.isLoggedIn();
      });
    }
  }
  </code></pre>
  
  <p>So canActivate is processed with <code>authInfo.isLoggedIn()</code> being <code>false</code> and after a fraction of a second I see <code>Got the uid</code> in the console. Any ideas how to prevent the first <code>false</code>? I think that BehaviorSubject is correctly used here, because it allows us to set an initial state. However the auth-guard will always receive false (the initial value). Right after that the</p>
  
  <pre><code>this.authInfo$.next(new AuthInfo(auth.uid));
  </code></pre>
  
  <p>will trigger, when the canActivate method was already finished.</p>