页面重新加载检查用户登录时的 angularfire2 身份验证状态 [英] angularfire2 auth state on page reload check user logged in

查看:24
本文介绍了页面重新加载检查用户登录时的 angularfire2 身份验证状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an angular4 app using angularfire2 and I'm having difficulty in finding out how to check if a user is logged in on page load. I can login and logout without issue, and I've implemented a guard on the router to prevent unauthorised access.

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

In an example I've found, the guard calls isLoggedIn in my auth service class, and checks if the user (AngularFireAuth) is not null. Since AngularFireAuth is of type Observable its never null so this doesn't work. How can I check if the user is logged in or not for my guard to work correctly?

这是我的身份验证服务类

Here's my auth service class

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

}

验证保护文件

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 {

  }
}

推荐答案

你可以在 auth 服务类中试试这个代码

You can try this code in auth service class

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

在你的组件中

声明一个 Observable isLoggedIn$:Observable;

declare an Observable isLoggedIn$:Observable<boolean>;

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

现在你可以订阅 observable

now you can subscirbe to the observable

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

这篇关于页面重新加载检查用户登录时的 angularfire2 身份验证状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆