I am trying to implement DELETE
operation in an angular app. I want to be able to click a button and have a firestore doc deleted but my code isn't working. So I'm using a service for all my firestore operations and calling the service in my component
station.service.ts
import { Injectable } from "@angular/core";
import { AngularFirestore } from "@angular/fire/firestore";
import { Station } from "../../models/station.model";
@Injectable({
providedIn: "root"
})
export class StationService {
constructor(private afs: AngularFirestore) {}
deleteStation(stationId: string) {
this.afs.doc("stations/" + stationId).delete();
}
}
station.component.ts
import { Component, OnInit } from "@angular/core";
import { StationService } from "../services/station.service";
import { Station } from "./../../models/station.model";
@Component({
selector: "app-station",
templateUrl: "./station.component.html",
styleUrls: ["./station.component.css"]
})
export class StationComponent implements OnInit {
stations: Station[];
constructor(private stationService: StationService) {}
ngOnInit() {
this.stationService.getStations().subscribe(data => {
this.stations = data.map(e => {
return {
id: e.payload.doc.data(),
...e.payload.doc.data()
} as Station;
});
});
}
delete(id: string) {
if (confirm("Confirm delete operation")) {
//console.log(id);
this.stationService.deleteStation(id);
}
}
}
I cannot find an id in my console.log message, it looks like this
address: "Somewhere along PTI road, Effurun. Delta State"
name: "Effurun"
region: "South-South"
How can i fix my code? Alert, this is my first time working with firestore.
Finally found the bug. In station.component.ts
ngOnInit() method, id was set to an object instead of an id. Set that to id like so
ngOnInit() {
this.stationService.getStations().subscribe(data => {
this.stations = data.map(e => {
return {
id: e.payload.doc.id,
...e.payload.doc.data()
} as Station;
});
});
}
Now an actual id of type string will be returned along with each object which can then be passed into delete(id: string)
method.