Search code examples
firebaseangular8angular-router-guards

Angular8 AngularFireAuth: authState.map for Guard canActivate() error: Property 'map' does not exist on type 'Observable<User>'


I have an error with Angular8 AngularFireAuth when trying to define canActive() on a guard

I get an error:

Property 'map' does not exist on type 'Observable'.ts(2339)

import { Injectable } from "@angular/core";
import { CanActivate, Router } from '@angular/router';
import { AngularFireAuth } from 'angularfire2/auth';
import { Observable } from 'rxjs';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private router: Router, private afAuth: AngularFireAuth) { }

  canActivate(): Observable<boolean> {
    this.afAuth.authState.map(auth => {
      if(!auth) {
        this.router.navigate(['/login']);
        return false;
      } else {
        this.router.navigate(['/']);
        return true;
      }
    })
  }
}

Solution

  • import { Injectable } from "@angular/core";
    import { CanActivate, Router } from '@angular/router';
    import { AngularFireAuth } from 'angularfire2/auth';
    import { Observable } from 'rxjs';
    import { map } from 'rxjs/operators'
    
    @Injectable()
    export class AuthGuard implements CanActivate {
      constructor(private router: Router, private afAuth: AngularFireAuth) { }
    
      canActivate(): Observable<boolean> {
        return this.afAuth.authState.pipe(map((user)=>{
          if(user) {
            return true;
          }
          this.router.navigate(['/login'])
          return false;
        }))
      }
    }