Search code examples
angularobservable

ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'pipe')


so I am facing a problem when I try to retrieve data from Observable in route guard service.

Angular thinks it is undefined.

Does anyone know what I did in wrong ?

Thanks in advance

AuthService file:

import { FirebaseApp } from '@angular/fire/app';
import { BehaviorSubject, Observable, take } from 'rxjs';
import { Auth, getAuth, GoogleAuthProvider } from "firebase/auth";

export class AuthService {

afAuth: Auth;
fireBaseUser$ : Observable<UserInfo>;  //Firebase User

constructor(private afApp: FirebaseApp, private route: 
ActivatedRoute){
this.afAuth = getAuth(this.afApp);
    this.afAuth.onAuthStateChanged((x)=>{
      this.fireBaseUser$ = new Observable<UserInfo>((observer)=>{
        observer.next(x);
      })
    })
}
}

enter image description here

AuthGaurd Service:

import { AuthService } from './auth.service';
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';

export class AuthGaurd implements CanActivate {

constructor(private auth:AuthService, private router: Router){}

canActivate(route, state:RouterStateSnapshot): Observable<boolean>{

return this.auth.fireBaseUser$.pipe(map((result)=>{
  console.log(result);
  if(result){
    return true
  }else{
    this.router.navigate(['/login'])
    return false;
  }
})
)

}

}

enter image description here

Error

enter image description here


Solution

  • set firBaseUser$ variable as BehaviorSubject and give it a default value, something like this:

     this.fireBaseUser$ = new BhaviorSubject(null);
    

    and then you can listen to it by convert it to Observable in your guard

    this.auth.fireBaseUser$.asObservsble().pipe ....