angularfire2 auth state on page reload check user登录

时间:2017-11-20 19:02:59

标签: angular angularfire2

我有一个使用angular4的{​​{1}}应用,我很难找到如何检查用户是否在页面加载时登录。 我可以毫无问题地登录和注销,并且我在路由器上实施了一个防护,以防止未经授权的访问。

在我发现的示例中,警卫在我的auth服务类中调用isLoggedIn,并检查用户(AngularFireAuth)是否为空。由于angularfire2的类型为AngularFireAuth,因此它永远不会为空,因此这不起作用。 如何检查用户是否已登录以使我的后卫正常工作?

这是我的授权服务类

Observable

Auth Guard文件

import { NotificationService } from './notification.service';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import * as firebase from 'firebase/app';
import { Injectable } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import { _firebaseAppFactory } from 'angularfire2/firebase.app.module';


@Injectable()
export class AuthService {

  private _user: Observable<firebase.User>;
  private _userDetails: firebase.User;
  private _success: boolean;

  constructor(private _firebaseAuth: AngularFireAuth, private _router: Router, private _notifier: NotificationService) {
    this._user = _firebaseAuth.authState;
    _firebaseAuth.authState.subscribe((user: firebase.User) => {
      console.log(user);
      this._userDetails = user;
    })
  }

  get user() {
    return this._user;
  }

  isLoggedIn() {
    if (this.user == null) {
      return false;
    } else {
      return true;
    }
  }


  login(email: string, password: string) {
    this._notifier.display(false, '');
    this._firebaseAuth.auth.signInWithEmailAndPassword(email, password).then((user: firebase.User) => {
      // if (user.emailVerified) {
      this._userDetails = user;
      this._router.navigate(['dashboard'])
      // }
    }).catch(err => {
      console.log('Something went wrong:', err.message);
      this._notifier.display(true, err.message);
    })
  }

  logout() {
    this._firebaseAuth.auth.signOut()
      .then((res) => {
        this._userDetails = null;
        this._router.navigate(['/login'])
      });
  }

}

1 个答案:

答案 0 :(得分:4)

您可以在auth服务类

中尝试此代码
isLoggedIn(): Observable<boolean> {
  return this._firebaseAuth.authState.map((auth) =>  {
        if(auth == null) {
          return false;
        } else {
          return true;
        }
      });
}

并在您的组件中

声明一个Observable isLoggedIn$:Observable<boolean>;

并在构造函数this.isLoggedIn$ = authService.isLoggedIn();

现在你可以替代可观察的

this.isLoggedIn$.subscribe(res => {
  if(res){
    console.log('user signed in');
  }else{
    console.log('user not signed in');
  }
});