【问题标题】:Storing user in database within Firestore将用户存储在 Firestore 中的数据库中
【发布时间】:2020-03-06 11:55:13
【问题描述】:

我正在使用 Firebase,但遇到了一些问题。创建新用户时,我可以将其存储在我的数据库中,但后来,当访问另一个组件时,它会失败。

//Register a new user in our system
  registerUserByEmail(email: string, pass: string) {
    return this.afAuth.auth
      .createUserWithEmailAndPassword(email, pass)
      .then(res => {
        this.email = res.user.email;
        let user = {
          email: this.email,
          goal: "",
          previousGoals: [],
          progress: {
            accomplishedToday: false,
            completedGoals: 0,
            daysInRow: 0,
            unlockedBadges: []
          }
        };
        // store in database
        new Promise<any>((resolve, reject) => {
          this.firestore
            .collection("users")
            .add(user)
            .then(
              res => {
                console.log(res.id);
                this.isAuthenticated = true;
                this.router.navigate(["/dashboard"]);
              },
              err => reject(err)
            );
        });
      });
  }

我相信这段代码基本上是将电子邮件注册为用户并将其成功存储到我的数据库中(检查过)。

不过,在渲染 home.component/dashboard

home.component

ngOnInit() {
    this.setAuthStatusListener();
    this.getUser();
  }

  getUser() {
    this.data.getUser().subscribe(user => {
      this.user = user.payload.data();
    });
  }

data.service

getUser() {
    return this.firestore
      .collection("users")
      .doc(this.currentUser.uid)
      .snapshotChanges();
  }

我收到以下错误 错误

TypeError: 无法读取 null 的属性 'uid'

【问题讨论】:

    标签: javascript angular firebase google-cloud-firestore firebase-authentication


    【解决方案1】:

    当您调用 getUser 时,用户似乎尚未通过身份验证。

    消除错误的简单方法是在 DataService 的 getUser 中检查这种情况:

    getUser() {
      if (this.currentUser) {
        return this.firestore
          .collection("users")
          .doc(this.currentUser.uid)
          .snapshotChanges();
      }
    }
    

    但是,鉴于此调用顺序,我认为可能有更好的方法来处理您的用例:

    ngOnInit() {
      this.setAuthStatusListener();
      this.getUser();
    }
    

    由于您是 attaching an auth state listener,您可能只想在用户实际通过身份验证后才开始在 Firestore 中查看用户数据。

    一种简单的方法是在用户通过身份验证后,从身份验证状态侦听器中调用 DataService 的 getUser() 方法。像这样的:

    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        this.getUser(); // call the DataService's getUser method
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 1970-01-01
      • 2020-08-08
      • 1970-01-01
      • 2020-04-16
      • 2019-08-01
      • 1970-01-01
      • 2016-07-25
      • 2021-09-05
      相关资源
      最近更新 更多