Reputation: 11
My entire Firebase Database is being dropped when attempting to a Delete Single Child from the Parent. My code is not effectively targeting the child record. [Angular 2 | Google Firebase]
HTML Section where Delete Button is Called This section cycles through all of the Profiles in the Firebase database and prints them to screen. I placed a delete button and included profile.key to pass the key value for the child profile to the fbRemoveProfile function.
<ul id="profile-listing">
<li *ngFor="let profile of profiles">
<div class="single-profile" style="text-align: center">
<p>First: {{profile.firstname}}<br>
Last: {{profile.lastname}}<br>
Email: {{profile.email}}<br>
Phone: {{profile.phone}}<br>
Industry: {{profile.industry}}</p>
<input type="button" value="Delete" class="btn btn-xs btn-danger" (click)="fbRemoveProfile(profile.key)">
<hr>
</div>
</li>
</ul>
Remove/Delete Function Definition
Here I am calling fbRemoveProfile. My console.logs show all snapshot.keys for the Firebase database when the delete button is depressed. I am unable to isolate the targeted profile key to the console. In either case, I am executing a general remove(); call which is dropping the database. Any recommendations would be much appreciated.
fbRemoveProfile(key){
firebase.database().ref('/').on('child_added', (snapshot) =>{
console.log('Delete button pressed')
console.log(snapshot.key)
snapshot.ref.remove();
});
}
Upvotes: 1
Views: 579
Reputation: 58430
Your fbRemoveProfile
function removes the entire database because the child_added
event on ref('/')
will:
be triggered once for each initial child at this location, and it will be triggered again every time a new child is added.
So remove
is called on every child of ref('/')
, deleting your database.
Instead, your function should be something like this:
fbRemoveProfile(key) {
return firebase.database().ref('profiles').child(key).remove();
}
Note that the child
method is used to obtain the child ref that's to be removed. This is safer than building a path to be passed to ref
, as the argument passed to child
is not allowed to be an empty string.
Upvotes: 1