CanActivate的AngularFire2(4.0)身份验证无效

时间:2017-05-21 22:01:21

标签: angular firebase firebase-authentication angularfire2

我根据以下教程构建了Angular 4 + FireBase(4.0.0.rc0)应用程序:https://coursetro.com/posts/code/32/Create-a-Full-Angular-Authentication-System-with-Firebase

本教程基于较旧版本的FireBase。我能够convert几乎所有东西到最新版本。我正在努力改变这种canActivate功能。它会导致Observable.from(this.afAuth)以下错误:

[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']);
      })
  }
}

我该如何做到这一点?

谢谢!

1 个答案:

答案 0 :(得分:9)

它应为afAuth.authState且已经Observable<firebase.User>,因此您不需要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']);
      }
    });
}