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

0

I'm developing an application with angular2 + angularfire2 + firebase, I'm experiencing difficulties in implementing authentication, I've been able to log in and out, but when the page is reloaded I lose authentication.

My 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 in starckoverflow, had commented on implementing firebase.auth () .onAuthStateChanged but I did not understand how to implement it.

    
asked by anonymous 15.05.2017 / 04:05

1 answer

0

Problem solved ...

When loaded, I would lose authentication, but when I navigate to another route it would come back, I do not know why this happened, but to solve my problem I ended up using #

    
24.05.2017 / 15:57