我正在尝试使用 Angular 在 Firebase 的 Firestore 中的文档内的集合中删除一个文档及其嵌套文档。截至目前,我可以删除上述文档和集合,但编译器不会向我抛出错误 error TS2339: Property 'id' does not exist on type '{}'
。错误代码可能是对的,也可能是错的,老实说我不知道,因为我的代码确实找到了与我正在查看的对象关联的 id。这是我的代码:
testID: string;
private testDoc: AngularFirestoreDocument<Test>;
constructor(private db: AngularFirestore) { }
deleteDoc() {
console.log('Deleting test');
this.db.collection(`tests/${this.testID}/questions`, ref => ref.orderBy('order'))
.valueChanges().subscribe(questions => {
questions.map(question => {
this.db.doc(`tests/${this.testID}/questions/${question.id}`).delete()
.catch(error => {console.log(error); })
.then(() => console.log(`tests/${this.testID}/questions/${question.id}`));
});
});
this.testDoc.delete().catch(error => console.log(error));
}
我也尝试在 map 函数中传递 2 个参数,但这只会在执行的函数而不是编译器中抛出错误,从而使代码根本无法工作(我可能没有在这里传递正确的东西)。
正如我所提到的,我的代码可以工作,但我肯定做错了什么。所以我的问题是,触发编译错误我做错了什么,如何在确保函数仍然有效的同时避免这种情况?希望有人可以帮助澄清我在这里做错了什么。
提前谢谢你。
*编辑,包括我正在查看的文档
export interface Question {
description: string;
order: number;
type: string;
id: string;
name: string;
options?: Object[];
radio_amount?: number;
current_chips?: Object[];
imageURL?: string;
}
最佳答案
我想我错过了我正在查看的变量的类型,但是我不知道如何在箭头函数中声明该变量的类型,因为尝试将外部变量包含到函数中对我不起作用.
我通过在此处的代码中添加类型来修复我的错误。现在代码像以前一样工作并且没有给我编译器错误。
deleteDoc() {
this.db.collection(`tests/${this.testID}/questions`,
ref => ref.orderBy('order')).valueChanges().subscribe(questions => {
questions.map((question: Question) => {
this.db.doc(`tests/${this.testID}/questions/${question.id}`).delete()
.catch(error => {console.log(error); })
.then(() => console.log(`Deleting question (${question.id}) in (${this.testID})`));
});
});
this.testDoc.delete().catch(error => console.log(error)).then(() => console.log(`${this.testID} has been deleted.`));
}
我很感谢你们中的一些人试图给我的帮助,但你们似乎更关注我的代码不起作用的事实,而事实并非如此或问题。重点是我在编译器抛出的问题中指定的错误,尽管函数正常工作,以及如何正确编写代码以不抛出错误。
请注意,我不建议使用上述功能,因为该功能当前在订阅问题集合时正在运行,因此当我在功能期间删除文档时,值会发生变化,因此还会多次运行代码.它有效,但未优化。
关于angular - 在 Firestore 中使用 Angular 删除集合中的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47422225/