AngularFire2 - 如何在页面刷新后保持登录状态

时间:2017-03-16 02:34:41

标签: javascript angular firebase firebase-authentication angularfire2

我正在使用AngularFire2作为应用程序,并且我已经使用Firebase注册/登录功能,但是,每次刷新页面时,登录状态都会重置并且不会持续存在。虽然我觉得我错过了一些非常小的东西,但我找不到能够做到这一点的功能。

我可以使用AngularFireAuth检查某处的页面加载吗?

这是我的身份验证提供程序代码:

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

    }

}

提前谢谢!

1 个答案:

答案 0 :(得分:3)

AppBundle\Entity\product: type: entity table: product id: id: type: integer generator: strategy: AUTO 是一个可观察的,并会发出AngularFireAuth个值。如果用户已登录并且页面已刷新,则FirebaseAuthState将发出经过身份验证的AngularFireAuth;否则,它会发出FirebaseAuthState

所以这样的事情应该接近解决你的问题:

null