我是Angular 4和Firebase的新手。我使用angular 4和firebase创建了一个身份验证项目。我能够创建一个用户,并且能够登录新创建的用户。
用户登录后,我按预期获得用户的authstate
。问题当我刷新页面或在我的角度CLI中执行ng serve
时发生。该应用重新加载,我的登录用户成为访客用户。
这是我的authenticationService.ts
文件。
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);
})
}
}
答案 0 :(得分:2)
而不是使用此变量管理authState:
authState: any = null;
在您的服务中加入此功能。我为此目的使用它,它返回一个Promise。
isLoggedIn(){
var promise = new Promise((resolve, reject) => {
this.afAuth.authState.subscribe(res => {
if (res && res.uid) {
console.log('user is logged in');
resolve(true);
} else {
console.log('user not logged in');
resolve(false);
}
});
});
return promise;
}
您可以在主要组件中使用它:
this.auth.isLoggedIn().then((val) => {
if(val){
console.log('loggedIn');
}else{
console.log('not loggedIn');
}
}
默认情况下,firebaseAuth会将会话存储在LocalStorage中,因此您在页面刷新后不会松开它,因为这是检索会话的正确方法。