Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularFire2 (4.0) authentication with CanActivate not working

I'm building an Angular 4 + FireBase (4.0.0.rc0) application based on the following tutorial: https://coursetro.com/posts/code/32/Create-a-Full-Angular-Authentication-System-with-Firebase

The tutorial is based on a older version of FireBase. I was able to convert almost everything to the latest version. I'm struggling with transforming this canActivate function. It throws on Observable.from(this.afAuth) the following error:

[ts]
Argument of type 'AngularFireAuth' is not assignable to parameter of type 'ArrayLike<{}>'.
Property 'length' is missing in type 'AngularFireAuth'.
(property) AuthGuard.afAuth: AngularFireAuth
export class AuthGuard implements CanActivate {

  constructor(private afAuth: AngularFireAuth, private router: Router) { }

  canActivate(): Observable<boolean> {
    return Observable.from(this.afAuth)
      .take(1)
      .map(state => !!state)
      .do(authenticated => {
        if
         (!authenticated) this.router.navigate(['/login']);
      })
  }
}

How can I make this work?

Thanks!

like image 599
Bernd Verhofstadt Avatar asked Jul 01 '26 17:07

Bernd Verhofstadt


1 Answers

it should be afAuth.authState and it's already Observable<firebase.User> so you don't need Observable.from

constructor(private afAuth: AngularFireAuth, private router: Router) { }

canActivate(): Observable<boolean> {
  return this.afAuth.authState
    .take(1)
    .map(authState => !!authState)
    .do(authenticated => {
      if (!authenticated) {
        this.router.navigate(['/login']);
      }
    });
}
like image 63
faruk Avatar answered Jul 03 '26 08:07

faruk