title: Async authguard in angular 6
body: <p>I would like to provide a server-side authentication before I give access to a specific route in angular.</p>
  
  <p>I have a AuthGuard which implements CanActivate and a service AuthService.
  The authService already has a <code>private loggedIn: BehaviorSubject&lt;boolean&gt; = new BehaviorSubject&lt;boolean&gt;(null);
  </code> which views subscribe to in order to know if the user is logged in or not. I don't really know if my approach is wrong, but it does not seem to work.</p>
  
  <p>This is what I have in auth.guard.ts:</p>
  
  <pre><code>canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) : Observable&lt;boolean&gt; {
      return this.authService.isAuthenticated().map((isLoggedIn) =&gt; {
          if (isLoggedIn) {
              return true;
          } else {
              this.router.navigate(['/login']);
              return false;
          }
      })
  }
  </code></pre>
  
  <p>and this is auth.service.ts:</p>
  
  <pre><code>    @Injectable()
  export class AuthService {
      private loggedIn: BehaviorSubject&lt;boolean&gt; = new BehaviorSubject&lt;boolean&gt;(null);
  
      constructor(
          private router: Router,
          private http: HttpClient
      ) {
  
      }
  
      get isLoggedIn() {
          return this.loggedIn.asObservable();
      }
  
      isAuthenticated() : Observable&lt;boolean&gt; {
          const headers = new HttpHeaders().set("X-Requested-With", "XMLHttpRequest");
  
          return this.http.get('/user', {headers: headers}).map(
              response =&gt; {
                  if (response['username']) {
                      this.loggedIn.next(true);
                      return true;
                  } else {
                      return false;
                  }
              }
          )
      }
  </code></pre>