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

查看:53
本文介绍了页面上的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)是否不为null.由于AngularFireAuth的类型为Observable,因此它永远不会为null,因此这是行不通的. 我该如何检查用户是否已登录,以使我的警卫正常工作?

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

}

Auth Guard文件

Auth Guard File

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

以及您的组件中

声明一个可观察的isLoggedIn$:Observable<boolean>;

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

现在您可以订阅可观察的

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天全站免登陆