【问题标题】:Delete data from Firestore using Angular使用 Angular 从 Firestore 中删除数据
【发布时间】:2020-12-22 08:53:38
【问题描述】:

我试图从 Firestore 中删除数据,获取和添加数据工作正常,但是当我尝试删除数据时,它并没有被删除,甚至在控制台上也没有显示任何错误。我们将不胜感激。

我的服务.ts

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();
}

}

组件.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);
  }

}

用户.ts

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

【问题讨论】:

  • 您可能应该在此处将集合名称更改为usersthis.userscollection = this.afs.collection('poetry');
  • 对不起,但在我看来,这不会有什么不同,因为诗歌是我在数据库中的收藏名称,如果我将其更改为用户,它不会获取数据。
  • this.userDoc = this.afs.doc('users/${user.id}'); 你不是在删除时使用users 集合名称吗?
  • this.userDoc = this.afs.doc('users/${user.id}'); 应该是this.userDoc = this.userscollection.doc(user.id); 我猜...
  • CollectionReference.doc() 出现错误要求其第一个参数为非空字符串类型,但它是:“”

标签: angularjs angular firebase google-cloud-firestore angularfire


【解决方案1】:

请更新您的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);
}

如果您想删除现有用户,您应该以同样的方式使用此集合。 您为什么不尝试将您的删除方法更新为这样的:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 2018-04-23
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 2020-04-28
    相关资源
    最近更新 更多