使用Angular从Firestore删除数据

问题描述

enter image description here

我正在尝试从Firestore中删除数据,获取添加数据的工作情况很好,但是当我尝试删除数据时,它并未删除,甚至在控制台上均未显示任何错误。帮助将不胜感激。

我的服务。

userscollection: AngularFirestoreCollection<User>;
users: Observable<User[]>;
userDoc: AngularFirestoreDocument<User>;

constructor(private afs: AngularFirestore) {
this.userscollection = this.afs.collection('poetry');
this.users = this.userscollection.snapshotChanges().pipe(map(actions => actions.map(a => {
  const data = a.payload.doc.data();
  const id = a.payload.doc.id;
  return { id,...data };
  })))
 }

getUsers() {
  return this.users;
}

addUser(user: User) {
  this.userscollection.add(user);
}

deleteUser(user: User) { 
  this.userDoc = this.afs.doc('users/${user.id}');
  this.userDoc.delete();
}

}

Component.ts

export class PoetryComponent implements OnInit {

user: User = {
  id: '',name: '',content: ''
}
users: User[];

constructor(private afs: AngularFirestore,public fb: FormBuilder,private userService: CrudService) 
{}

ngOnInit() {
  this.userService.getUsers().subscribe(users => {
  this.users = users;
  })
 }

onSubmit() {
  this.userService.addUser(this.user);
  this.user.name='';
  this.user.content='';
}

 deleteUseRSS(event,user) {
  this.userService.deleteUser(user);
  }

}

User.ts

export class User {
 public constructor(public id: string,public name: string,public content: string) {
  }
}

解决方法

请更新您的service.ts文件。根据课程https://fireship.io/courses/angular/,您必须获取文档参考,然后将其删除。请在这里https://github.com/codediodeio/angular-firestarter/blob/ebc7b2b8764459d57609fb4e79e3675d8f770ab4/src/app/kanban/board.service.ts#L60看看它是如何完成的。

因此,在您的情况下,您具有对用户集合的引用(我不知道为什么称其为poetry,您应该在Firestore中将其命名为users还是poetryCollection在您的代码中)

this.userscollection = this.afs.collection('poetry');

在添加我用户时,您正在使用此收藏集:

addUser(user: User) {
  this.userscollection.add(user);
}

如果要删除现有用户,则应以相同的方式使用此集合。 为什么不尝试将您的delete方法更新为以下内容:

deleteUser(user: User) { 
  this.userscollection.doc(user.id).delete();
}
  • 使用指向您的Firestore中的usercollection集合的poetry
  • 通过ID获取对用户的引用,
  • 删除它。