我尝试在身份验证后在Firebase数据库中创建用户。这是一个例子:
组件:
regGoogle() {
this.af.auth.login({
provider: AuthProviders.Google,
method: AuthMethods.Redirect,
})
//Need to invoke this AFTER auth
this.memberCreationService.regGoogle(
auth.auth.providerData[0].email,
auth.auth.providerData[0].displayName,
auth.auth.providerData[0].photoURL,
auth.uid
)
}
我的服务:
regGoogle(
email: string, displayName: string, photoUrl: string, uid: string) {
let member: Object = {
email: email,
displayName: displayName,
picture: photoURL
}
this.af.database.object(`/members/${uid}`).update(member)
}
最初,我在我的服务构造函数中调用了regGoogle()
,只是为了这个基本功能:
this.af.auth.subscribe(auth => {
this.auth = auth;
if (auth) {
this.regGoogle(
auth.auth.providerData[0].email,
auth.auth.providerData[0].displayName,
auth.auth.providerData[0].photoURL,
auth.uid
)
}
})
显然,这对于真正的应用来说并不是很好。首先,它不分青红皂白地调用regGoogle()
。但我的具体问题是无论我是想登录还是注册,都会创建用户。因为,对于提供者,auth上没有寄存器方法,这使得有必要确定用户是否已经存在于用于注册/登录的任何方法中。
因此,我们的目标是为每个提供商提供单独的方法,以及我是否尝试登录或注册。这样做的原因是为了避免覆盖和现有用户。不是,只是这个过于复杂,这要求每个操作都必须执行,并且似乎不能使用异步FirebaseAuthState。
我最终整合了注册/登录方法,并在服务收到authstate发射后立即在我的服务构造函数中调用它们,就像我之前做的那样,但检查用户是否存在于注册/登录中方法
loginProvider() {
let member: Object = {
email: this.auth.auth.providerData[0].email,
displayName: this.auth.auth.providerData[0].displayName,
picture: this.auth.auth.providerData[0].photoURL
}
this.af.database.object(`members/${this.auth.uid}`)
.take(1)
.subscribe(data => {
if(data.$value === null) {
this.af.database.object(`members/${this.auth.uid}`).update(member)
this.router.navigate(['member-creation'])
} else {
console.log('Thanks for logging in, ' + this.auth.auth.providerData[0].displayName)
this.router.navigate(['threads/featured'])
}
})
}
我很乐意听到有关此实施的任何意见。