【发布时间】:2018-04-15 20:02:41
【问题描述】:
我是 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);
})
}
}
【问题讨论】:
-
我只真正处理了 oauth google login with angular not firebase 但在我的情况下,我需要将登录信息保存到 sessionStorage 或 localStorage。
-
我已经在这个问题中尝试了 tlocal 存储..但刷新时 authstate 仍然发生变化..
标签: angular firebase firebase-authentication angularfire2