I am new to Angular 4 and Firebase. I have created an authentication project using angular 4 and firebase. I am able to create a user and as well as able to sign in the newly created user.
After user logs in I get the authstate
of the user as expected. Issue Occurs when I refresh the page or do ng serve
in my angular CLI. The app reloads and my signed in user becomes a guest user.
This is my authenticationService.ts
file.
import { Injectable } from '@angular/core';
import { Router } from "@angular/router";
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFireDatabaseModule, AngularFireDatabase } from
'angularfire2/database';
import * as firebase from 'firebase/app';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class AuthService {
authState: any = null;
constructor(private afAuth: AngularFireAuth,
private db: AngularFireDatabase,
private router:Router,
) {
this.afAuth.authState.subscribe((auth) => {
this.authState = auth;
});
}
// Returns true if user is logged in
get authenticated(): boolean {
return this.authState !== null;
}
// Returns current user data
get currentUser(): any {
return this.authenticated ? this.authState : null;
}
// Returns
get currentUserObservable(): any {
return this.afAuth.authState;
}
// Returns current user UID
get currentUserId(): string {
return this.authenticated ? this.authState.uid : '';
}
// Returns current user display name or Guest
get currentUserDisplayName(): string {
if (!this.authState) {
return 'Guest';
} else if (this.currentUserAnonymous) {
return 'Anonymous';
} else {
return this.authState.email.substr(0, this.authState.email.indexOf('@'));
}
}
//// Email/Password Auth ////
// SignUp
emailSignUp(email: string, password: string, uname: string) {
return this.afAuth.auth.createUserWithEmailAndPassword(email, password).then((user) => {
this.authState = user
this.router.navigate(['/signin']);
console.log('Registered Successfully ');
}).catch(error => console.log(error));
}
//SignIn
emailLogin(email:string, password:string) {
return this.afAuth.auth.signInWithEmailAndPassword(email, password).then((user) => {
this.authState = user
console.log("user details:",user);
this.router.navigate(['/home']);
console.log('Successfully Signed In');
}).catch((error) => console.log(error));
}
//// Sign Out ////
userSignOut(){
this.afAuth.auth.signOut()
.then((success) => {
this.router.navigate(['/signin'])
console.log(firebase.auth().currentUser);
}).catch((error) =>{
console.log(error);
})
}
}