首页 > 解决方案 > Angular - 将firestore文档移动到另一个集合问题

问题描述

我正在尝试使用 AngularFirestore 将文档从一个集合移动到另一个集合。

终于过了一段时间,我想出了一个可行的解决方案:

    // Subscribing to original document to get data
    this.afs.collection('boards').doc(this.boardId)
            .collection('categories').doc(this.categoryId)
            .collection('taskList').doc(id)
            .valueChanges().subscribe((task: Task) => {

      // Adding a copy of document into desired category
      this.afs.collection('boards').doc(this.boardId)
              .collection('categories').doc('doneList')
              .collection('taskList').doc(id)
              .set({name: task.name, description: task.description, authorId: task.authorId, creationDate: task.creationDate,
                    lastEditorId: task.lastEditorId, lastEditDate: task.lastEditDate,
                    isApproved: taskApproved, points: task.points, completitorId: this.userId, completitionDate: new Date()});

    });

    // Deleting task in original category
    this.afs.collection('boards').doc(this.boardId)
            .collection('categories').doc(this.categoryId)
            .collection('taskList').doc(id).delete();

它正在工作,问题是,当我删除原始文档时,它会产生一个错误:

"ERROR TypeError: Cannot read property 'name' of undefined".

我很确定它是由删除订阅的文档引起的,所以我试图以各种方式取消订阅它,使用then()函数来处理删除等等。到目前为止没有任何帮助。

我该如何以正确的方式处理它?

标签: angulargoogle-cloud-firestore

解决方案


当你调用 subscribe() 时,它会返回一个 Subscription 对象,你应该坚持:

subscription = this.afs.collection(...)...snapshotChanges().subscribe();

然后,当您不再需要更新时,您可以使用它来取消订阅:

subscription.unsubscribe()

在您的订阅侦听器中,为了安全起见,您可能还只想防范未定义task的值。

if (task) {
    // only work with task here
}

推荐阅读