首页 > 解决方案 > 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;
      }
    );
  }

我该怎么做呢?我到处搜索,找不到任何解决方案。这实际上是正确的方法吗?如果有更好的方法请告诉我!

标签: javascriptangularfirebasefirebase-authenticationangularfire2

解决方案


您可以使用您的身份验证服务来存储从 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 应用程序的根级别使用全局数据服务来存储用户详细信息。


推荐阅读