AngularFire2 - How to keep login state after page refresh

I use AngularFire2 for the application, and I got the registration / login functions with Firebase, however every time I refresh the page, the registered state is reset and will not be saved. I cannot find the functionality, but I feel that I have something very small.

Is it possible to use AngularFireAuth to check page load somewhere?

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

Thank you in advance!

+3
source share
1 answer

AngularFireAuth is observable and emits FirebaseAuthState values. If the user is registered and the page is updated, AngularFireAuth will issue 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); } }); } 
+3
source

Source: https://habr.com/ru/post/1268074/


All Articles