VMA VMA - 2 months ago 11
TypeScript Question

Firebase: remove child element is not working

I have already tried different kind of solutions to remove child element by key from Firebase-Database, but without any effect. What I am doing wrong?

My database structure looks like this, where

is under the root of the database
enter image description here

I have an Angular 2 Single Page Application, where in the index.html included FireBase-client initialization:

<script src="https://www.gstatic.com/firebasejs/3.5.3/firebase.js"></script>
// Initialize Firebase
var config = {/*....*/};

Regardless Firebase documentation both deletions are not working:

removePlayer1(id: any): Promise<Response> {
return firebase.database().ref("players").child(id).once('value')
.then((snap: any) => {
console.log("Player was removed", id, snap);
}).catch((err: any) => this.handleError(err));

removePlayer2(id: any): Promise<Response> {
return firebase.database().ref().child('players')
.child(id).remove().then((r: any) => {
console.log("Player was removed", id);
}).catch((err: any) => this.handleError(err));

This solution still is not working:

removePlayer(id: any): Promise<Response> {
var updates = {};
updates[id] = null;
return firebase.database().ref("players").update(updates)
.then((r: any) => {
console.log("Player was removed", id, r);
}).catch((err: any) => this.handleError(err));

At the same time update and insert child values perfectly works:

savePlayer(player: IPlayer): Promise<Response> {
let playerRef: any;
if (!player._id) {
playerRef = firebase.database().ref().child('players').push().set(player);
} else {
var updates = {};
updates[player._id] = player;
playerRef = firebase.database().ref().child('players').update(updates);

return playerRef.catch((err: any) => this.handleError(err));



I don't know why the mentioned link from StakOverflow didn't help me, but I was near and as a result my solution looks like this:

removePlayer(id: any): Promise<any> {
    var ref = firebase.database().ref().child('players');
    return new Promise<any>((resolve, reject) => {
        ref.child(id).once("value", function (snapshot: any) {
            var updates = {};
            updates[snapshot.key] = null;
            ref.update(updates).then((r: any) => {
            }).catch((e: any) => reject(e));
        }).catch((e: any) => reject(e));