首页 文章

angularfire2 auth state on page reload check user登录

提问于
浏览
0

我有一个使用 angularfire2angular4 应用程序,我在路由器上实施了一个防护,以防止未经授权的访问 .

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

这是我的auth服务类

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

}

Auth Guard文件

import { AngularFireAuth } from 'angularfire2/auth';
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service';

@Injectable()
export class AuthGuard implements CanActivate {

  isLoggedIn$: Observable<boolean>;

  constructor(private _auth: AuthService, private _router: Router, private _firebaseAuth: AngularFireAuth) {
    this.isLoggedIn$ = _auth.isLoggedIn();

    this.isLoggedIn$.subscribe(res => {
      if (res) {
        console.log("is logged in");
      } else {
        console.log("is not logged in");
      }
    });
  }

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

  }
}

1 回答

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

相关问题