Persist logged in with angularfire2 using cookies

I am using simple user authentication using angularfire2 and the Firebase authentication service.

import { Injectable } from '@angular/core';
import { AngularFire } from 'angularfire2';
import { Cookie } from 'ng2-cookies';

@Injectable()
export class GlobalMenuService {

    loggedIn: boolean = false;

    constructor(private af: AngularFire) { }

    login(email: string, password: string) {
        this.af.auth.login({
            email: email,
            password: password
        })
            .then((success) => {
                this.loggedIn = true;
            });
    }

    logout() {
        this.af.auth.logout();
        this.loggedIn = false;
    }
}

Is there a way to store some data in a cookie (token, uid, email, or something else) to restore the session, i.e. every time the user returns to the application, log in again without having to enter credentials?

+4
source share
1 answer

You must use auth.subscribe(). This function will be called at any time when the authentication state changes.

this.af.auth.subscribe(user => {
  if (user) {
    // User is signed in.
    ... do other stuff
  } else {
    // No user is signed in.
    ... do other stuff
  }
});

signInWithEmailAndPassword, , auth .

+3

All Articles