firebase.auth(). currentUser returns null when reloading the page

Asked

Viewed 359 times

0

I’m developing an application with angular2 + angularfire2 + firebase, I am facing difficulties in implementing authentication, I was able to login and logout, but when the page is reloaded I lose authentication.

Meu Seriço.

import {Injectable, OnChanges, OnInit} from '@angular/core';
import {AngularFireAuth} from 'angularfire2/auth';
import * as firebase from 'firebase/app';
import {Router} from "@angular/router";


@Injectable()
export class LoginService {

static isLoggedIn: boolean;


constructor(private router: Router, public afAuth: AngularFireAuth) {

    firebase.auth().onAuthStateChanged(function(user) {
        if (user) {
            LoginService.isLoggedIn = true;
        } else {
            LoginService.isLoggedIn = false;
        }
    });

}

login(email: string, password: string) {
    firebase.auth().signInWithEmailAndPassword(email, password).then((data => {
        LoginService.isLoggedIn = true;

        this.router.navigate(['dashboard']);
    })).catch(function (error) {
        // Handle Errors here.
        console.log(error.message);

    });

}

logout() {
    this.afAuth.auth.signOut();
}

}

My Guard:

import {Injectable} from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot,         
Router} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import {LoginService} from '../login/login.service';
import {AngularFireAuth} from "angularfire2/auth";
import * as firebase from 'firebase/app';


@Injectable()
export class AuthGuard implements CanActivate {

constructor( private router: Router) {
}

canActivate(next: ActivatedRouteSnapshot,
            state: RouterStateSnapshot): Observable<boolean> | 
Promise<boolean> | boolean {
    if(LoginService.isLoggedIn){
        return true;
    }else{
        this.router.navigate(['login']);
        return false;
    }
}
}

I took a look at problems similar to mine here at starckoverflow, had commented on implementing firebase.auth(). onAuthStateChanged however did not understand how to implement it.

1 answer

0


Problem Solved...

When loaded I lost the authentication, but when I navigated to another route it returned, I don’t know why it happened, but to solve my problem I ended up using localStorange, now when I just in the system I save a variable and it is checks if it exists, and when I log out I delete my variable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.