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.