Reputation: 13
I was trying to delete data from firestore, the fetching and adding data is working perfectly fine but when i try to delete data its not deleting and not even shows any error on console. Help will be appreciated.
My service.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();
}
}
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) {
}
}
Upvotes: 0
Views: 2152
Reputation: 1490
Please update your service.ts
file. According to this course https://fireship.io/courses/angular/ you have to fetch the document reference and then delete it. Please take a look on how it's done here https://github.com/codediodeio/angular-firestarter/blob/ebc7b2b8764459d57609fb4e79e3675d8f770ab4/src/app/kanban/board.service.ts#L60.
So in your case, you have the reference to users collection (I don't know why you call it poetry
, you should either call it users
in the firestore or poetryCollection
in your code)
this.userscollection = this.afs.collection('poetry');
While adding me user you're using this collection:
addUser(user: User) {
this.userscollection.add(user);
}
If you want to delete an existing user you should use this collection in the very same way. Why don't you try to update your delete method to something like this:
deleteUser(user: User) {
this.userscollection.doc(user.id).delete();
}
usercollection
that points to poetry
collection in your firestore,Upvotes: 2