AngularFire2 - How to maintain logged in state aft

2020-06-23 13:47发布

问题:

I'm using AngularFire2 for an app and I've gotten the registration/login functionality working with Firebase, however, every time I refresh the page, the logged in state is reset and won't persist. I can't quite find functionality to do this, though I feel I'm missing something very small.

Can I use the AngularFireAuth to check on page load somewhere?

Here is my auth provider code:

import { Injectable } from '@angular/core';
import {Observable, Subject, BehaviorSubject} from "rxjs/Rx";
import {AngularFireAuth, FirebaseAuthState} from "angularfire2";
import {AuthInfo} from "./auth-info";
import {Router} from "@angular/router";

@Injectable()
export class AuthService {


  static UNKNOWN_USER = new AuthInfo(null);

  authInfo$: BehaviorSubject<AuthInfo> = new BehaviorSubject<AuthInfo>(AuthService.UNKNOWN_USER);


  constructor(private auth: AngularFireAuth, private router:Router) {

  }

    login(email, password):Observable<FirebaseAuthState> {
        return this.fromFirebaseAuthPromise(this.auth.login({email, password}));
    }


    signUp(email, password) {
        return this.fromFirebaseAuthPromise(this.auth.createUser({email, password}));
    }


    fromFirebaseAuthPromise(promise):Observable<any> {

        const subject = new Subject<any>();

        promise
            .then(res => {
                    const authInfo = new AuthInfo(this.auth.getAuth().uid);
                    this.authInfo$.next(authInfo);
                    subject.next(res);
                    subject.complete();
                },
                err => {
                    this.authInfo$.error(err);
                    subject.error(err);
                    subject.complete();
                });

        return subject.asObservable();
    }


    logout() {
        this.auth.logout();
        this.authInfo$.next(AuthService.UNKNOWN_USER);
        this.router.navigate(['/login']);

    }

}

Thankyou in advance!

回答1:

AngularFireAuth is an observable and emits FirebaseAuthState values. If a user is signed in and the page is refreshed, AngularFireAuth will emit an authenticated FirebaseAuthState; otherwise, it will emit null.

So something like this should come close to solving your problem:

constructor(private auth: AngularFireAuth, private router:Router) {

  auth.subscribe((authState) => {
    if (authState) {
      const authInfo = new AuthInfo(authState.uid);
      this.authInfo$.next(authInfo);
    }
  });
}