将用户存储在Firestore中的数据库中

我正在使用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”

服务

xuyuqun 回答:将用户存储在Firestore中的数据库中

在您致电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中查看用户的数据。

执行此操作的一种简单方法是,一旦对用户进行身份验证,就可以从auth状态监听器中调用DataService的getUser()方法。像这样:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    this.getUser(); // call the DataService's getUser method
  }
});
本文链接:https://www.f2er.com/3128552.html

大家都在问