3

我正在使用AngularFire2作爲應用程序,並且我已經獲得了使用Firebase的註冊/登錄功能,但是,每次刷新頁面時,登錄狀態爲重置並不會持續。我不能完全找到這樣做的功能,但我覺得我錯過了一些非常小的東西。AngularFire2 - 如何在頁面刷新後保持登錄狀態

我可以使用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']); 

    } 

} 

三江源提前!

回答

3

AngularFireAuth是一個可觀測值併發出FirebaseAuthState值。如果用戶已登錄且頁面已刷新,則AngularFireAuth將發出已驗證的FirebaseAuthState;否則,它會發出null

所以這樣的事情應該接近解決您的問題:

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

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

cartant,這可能是你幫助過我的第5次。有一天我會找到你......我會抱抱你。謝謝你這麼做了。你是最棒的! –

相關問題