繁体   English   中英

Angular/Firebase:如何将用户响应放入前端模型

[英]Angular/Firebase: How to put user response in front-end model

我对两者都是新手。 我的思考过程如下。 当我使用 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);
  }

登录.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 => {
        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 应用程序的根级别使用全局数据服务来存储用户详细信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM