Firebase:保持用户登录角度为7

时间:2019-02-24 19:18:57

标签: javascript angular firebase firebase-authentication angularfire2

我在身份验证系统中使用firebase和angularfire2!

问题是刷新后,用户需要再次登录!我需要避免该问题,因此我发现Firebase通过使用authState

给了我该选择

但仍然无法正常工作!

这是authService的代码:

import { Injectable } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import { Observable } from 'rxjs/internal/observable';
import { NavController } from '@ionic/angular';
import { ToastMessagesService } from './toast-messages.service';
import * as firebase from 'firebase';

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  public user: Observable<firebase.User>;
  public userDetails: firebase.User = null;


  constructor(
    private af: AngularFireAuth,
    private navCtrl: NavController,
    private statusMessage: ToastMessagesService
  ) {

    this.user = af.authState;

    this.user.subscribe(
      user => this.userDetails = user
    )


  }

  async siginInRegular(username: string, password: string) {
    try {

      // const credentials = this.af.auth.email
      return await this.af.auth.signInWithEmailAndPassword(username, password).then(
        user => {
          if (user) {
            this.navCtrl.navigateForward('/home');
            this.statusMessage.message(`Welcome ${user.user.email}`);
          }
        },
        err => {
          console.log(err);
        }
      );
    } catch (error) {
      console.dir(error);
    }
  }

  async register(username: string, password: string) {
    try {
      return await this.af.auth.createUserWithEmailAndPassword(username, password).then(
        user => {
          this.navCtrl.navigateForward('/profile');
          this.statusMessage.message(`Welcome ${user.user.email}`);
        }
      );
    } catch (error) {
      console.dir(error);
    }
  }

  signOut() {
    return this.af.auth.signOut();
  }

  isLoggedIn(): boolean {
    return (this.userDetails != null) ? true : false;
  }


}

保护代码:

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

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {



  constructor(
    private auth: AuthService,
    private navCtrl: NavController,
    private af: AngularFireAuth
  ) {

  }

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


    if (this.auth.isLoggedIn()) {
      return true
    }

    console.log('Access denied!');
    return false;

  }
}

1 个答案:

答案 0 :(得分:0)

Firebase实际上会在您重新加载页面时自动登录用户。但是,由于您仅在then()块中处理登录,因此只有在您明确登录后才会发生。

要解决此问题,您想使用get the currently signed in user中所示的onAuthState侦听器:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});

then()处理程序不同,此onAuthStateChanged处理程序将在用户的身份验证状态每次更改(包括重新加载页面时)时被调用。

由于您使用的是AngularFire2,因此也可以使用af.auth.subscribe,如下所示:How to get the firebase.User in AngularFire2