【问题标题】:Angular/Firebase: How to put user response in front-end modelAngular/Firebase:如何将用户响应放在前端模型中
【发布时间】:2019-12-18 14:54:24
【问题描述】:

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

login.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;
      }
    );
  }

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

【问题讨论】:

  • 您正在使用什么类型的应用程序?它是生产级应用还是分配级?
  • 这是作业级别。制作项目来教我自己真实世界的例子。深入了解代码等。
  • 非常感谢对此答案的支持...提前致谢
  • 我还没有足够的声誉来公开展示它。还需要两个。当我有足够的时候会做。顺便说一句,谢谢你的回答真的很有帮助!

标签: javascript angular firebase firebase-authentication angularfire2


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-01-28
    • 2021-03-07
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    • 2020-08-21
    • 2022-11-23
    • 1970-01-01
    • 2019-05-16
    相关资源
    最近更新 更多