我正在将Firebase与AngularFire 2一起使用。
我的问题是,当我尝试刷新页面时,auth实例返回null。
这是我的身份验证服务的代码。
一切正常,但是每当刷新页面时,auth为null,并且由于需要用户进行身份验证而无法调用firebase数据库。
export class AuthService {
private userDetails: Users = null;
private dbUsers;
public loginStatus = new BehaviorSubject(false);
public GOOGLE_OATH_SCOPES = 'email, https://www.googleapis.com/auth/drive';
constructor(
private _firebaseAuth: AngularFireAuth,
private router: Router,
private firebase: AngularFireDatabase,
private _userService: UserService
) {
var currentUser = JSON.parse(localStorage.getItem('currentUser'));
this.setUserFromLocalstorage(currentUser);
_firebaseAuth.authState.subscribe(
(user) => {
console.log("Step 1",user);
if (user) {
}
else {
this.setUserFromLocalstorage(currentUser);
}
}
);
}
setUserFromLocalstorage(currentUser) {
if (currentUser && !_.isEmpty(currentUser)) {
this.userDetails = currentUser;
} else {
this.userDetails = null;
};
}
signInWithGoogle() {
var provider = new firebase.auth.GoogleAuthProvider();
provider.setCustomParameters({
prompt: 'select_account'
});
provider.addScope(this.GOOGLE_OATH_SCOPES);
this._firebaseAuth.auth.setPersistence(firebase.auth.Auth.Persistence.NONE).then(() =>
this._firebaseAuth.auth.signInWithPopup(
provider
).then((result) => {
localStorage.setItem('accessToken', result.credential.accessToken);
})
)
}
isLoggedIn() {
if (!this.loginStatus.value) {
return false;
} else {
return true;
}
}
logout() {
this._firebaseAuth.auth.signOut()
.then((res) => {
this.router.navigate(['/'])
localStorage.clear()
this.userDetails = null;
this.loginStatus.next(false);
}
);
}
getLoggedInUser() {
return _.cloneDeep(this.userDetails);
}
setLoggedInUser(user: Users) {
this.userDetails = user;
localStorage.setItem("currentUser", JSON.stringify(user));
}
}
和AngularFireAuth:
export declare class AngularFireAuth {
private zone;
readonly auth: FirebaseAuth;
readonly authState: Observable<User | null>;
readonly idToken: Observable<string | null>;
constructor(config: FirebaseOptions, name: string, platformId: Object, zone: NgZone);
}
我的登录方法:
this._firebaseAuth.auth.setPersistence(firebase.auth.Auth.Persistence.None).then(() =>
this._firebaseAuth.auth.signInWithPopup(
provider
).then((result) => {
})
)
如何解决此问题?
答案 0 :(得分:1)
问题出在您的登录方法上。
this._firebaseAuth.auth.setPersistence(firebase.auth.Auth.Persistence.None).then(() =>
this._firebaseAuth.auth.signInWithPopup(
provider
).then((result) => {
})
)
第{{1}行”指出该状态将仅存储在内存中,并且在刷新窗口或活动时将清除该状态。
尝试使用setPersistence(firebase.auth.Auth.Persistence.None)
或firebase.auth.Auth.Persistence.Session
根据您的要求。
引用:https://firebase.google.com/docs/auth/web/auth-state-persistence