【问题标题】:AngularFire Cannot update document because document reference ID could not be fetchedAngularFire 无法更新文档,因为无法获取文档参考 ID
【发布时间】:2019-09-25 07:27:18
【问题描述】:

我正在制作一个更新函数,它将根据与经过身份验证的用户的 uid 相关联的文档 uid 获取所需的文档。

在另一个函数中,我使用相同的方法从集合中获取数据,该方法工作正常,但在我将 uid 作为变量存储的函数中,它作为 [object object] 返回我。

这是调用来检索我当前的用户数据的函数

this.user$ = this.afAuth.authState.pipe(
  switchMap(user => {
    if (user) {
      return this.afs.doc<any>(`users/${user.uid}`).valueChanges();
    } else {
      return null;
    }
  })
);

然后,这将通过简单地调用例如获得我需要的字段。用户名

但是,当尝试存储文档 uid 时

this.userID = this.afAuth.authState.pipe(
  switchMap(user => {
    if (user) {
      this.userID = user.uid;
    } else {
      return null;
    }
  })
); 

我的用户 ID 的值就是 [object object]

当调用它时

updateUser(user: User) {
    this.userDoc = this.afs.doc(`users/${this.userID}`);
    this.userDoc.update(user);
  }

返回一个未定义的文档路径 .../documents/users/[object Object]

然后我如何能够跟踪文档 ID 以进行更新?

【问题讨论】:

    标签: angular typescript firebase


    【解决方案1】:

    改变这个:

    this.userID = this.afAuth.authState.pipe(
      switchMap(user => {
        if (user) {
          this.userID = user.uid;
        } else {
          return null;
        }
      })
    ); 
    

    进入这个:

    this.userID = this.afAuth.authState.pipe(
      switchMap(user => {
        if (user) {
          this.userIDs= user.uid;
        } else {
          return null;
        }
      })
    ); 
    

    您需要使用不同的变量 (this.userIDs) 名称来存储 user.uid

    【讨论】:

    • 是否有理由需要声明一个新变量来解决这个问题?同样使用它只会给我一个未定义的结果
    • 你能做到console.log(user)
    • 使用 console.log(user) 它返回我从文档中获取和更新的数据字段,但是在 console.loh(this.usersID) 上它返回给我一个未定义的
    • 您在这里使用this.userID = this.afAuth.authState.pipe(this.userID = user.uid 这就是为什么我告诉您更改变量,因为它返回[object object] 这是this.afAuth.authState.pipe(
    • 当我将其设置为 this.userIDs= user.uid; 而不是 [object object] 时,我变得不确定。但是我传入的参数user 包含我要存储的字段数组
    【解决方案2】:

    问题是您存储了对this.userID 的赋值以及对this.userID 的订阅。删除分配:this.userID = this.afAuth.authState,现在它将正确存储!而是将订阅存储在另一个变量中,然后您可以在需要时取消订阅:

    this.mySubscription = this.afAuth.authState.pipe(
      switchMap(user => {
        if (user) {
          this.userID = user.uid;
        } else {
          return null;
        }
      })
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多