javascript - Angular/Firebase:如何将用户响应放在前端模型中
问题描述
我对两者都很陌生。我的思考过程如下。当我使用 Angular 登录到我的 Firebase 后端时,如果成功,我会向控制台发送响应。在此响应中,我可以看到 firebase 用户拥有的所有密钥。我想要做的是将这些链接到/在我的前端的用户模型中,以便在显示用户个人资料页面或其他内容时可以轻松访问它。(我不知道这是否也是正确的思考过程。如果您知道更好的解决方案,请以正确的方式轻推我)
auth.service.ts
constructor(
private angularFireAuth: AngularFireAuth,
) {
this.userData = angularFireAuth.authState;
}
signIn(email: string, password: string) {
return this.angularFireAuth.auth.signInWithEmailAndPassword(email, password);
}
登录组件.ts
signIn(email: string, password: string) {
this.spinnerButtonOptions.active = true;
email = this.loginForm.value.email;
password = this.loginForm.value.password;
this.auth.signIn(email, password).then(
res => {
console.log('signed in ', res);
this.router.navigate(['/dashboard']);
}
).catch(
error => {
console.log('something went wrong ', error);
this.formError = true;
this.spinnerButtonOptions.active = false;
}
);
}
我该怎么做呢?我到处搜索,找不到任何解决方案。这实际上是正确的方法吗?如果有更好的方法请告诉我!
解决方案
您可以使用您的身份验证服务来存储从 Firebase 后端返回的数据。或者,您可以将它存储在一个共享服务中,它在所有组件和模块中都可用。
在您的身份验证服务中:
@Injectable()
export class AuthService{
public usermodel:any;
constructor(private angularFireAuth: AngularFireAuth) {
this.userData = angularFireAuth.authState;
}
signIn(email: string, password: string) {
return this.angularFireAuth.auth.signInWithEmailAndPassword(email, password);
}
setLoggedInUserData(userDetails: any) {
this.usermodel = userDetails;
}
getLoggedInUserData() {
return this.usermodel;
}
}
在您登录 component.ts :
signIn(email: string, password: string) {
this.spinnerButtonOptions.active = true;
email = this.loginForm.value.email;
password = this.loginForm.value.password;
this.auth.signIn(email, password).then(
res => {
this.authService.setLoggedInUserData(res);
this.router.navigate(['/dashboard']);
}
).catch(
error => {
console.log('something went wrong ', error);
this.formError = true;
this.spinnerButtonOptions.active = false;
}
);
}
在您需要使用使用详细信息的其他组件中,注入 auth.service.ts 并使用该getLoggedInUserData()
方法获取登录用户的详细信息。
还有其他几种方法可以做到这一点。一种选择是使用 ngrx 存储实现。其他方法是在 Angular 应用程序的根级别使用全局数据服务来存储用户详细信息。
推荐阅读
- php - 查找并提取然后替换每个文件中的每一行
- android - Android Emoji App Compat Text View 不呈现某些表情符号,例如
- excel - 将excel工作表插入excel文件的Powershell代码
- java - JavaFX 警报对话框
- r - 样本的历史 - 在 R 中更改限制 x、y
- r - 根据条件向数据框添加列
- blazor - 如何处理托管它的组件/页面中的 Blazor 子组件中引发的异常?
- c# - DDD 删除聚合的最佳解决方案
- python - 使用 pyMongo 和 MongoEngine 从 MongoDb 列表中删除对象及其索引?
- java - 多个 MQTT 客户端订阅同一个主题