1

I am working on my first project in Angular and Firebase, I'm almost done.

I have a question on deleting objects using both. I have a service that will delete an object. The object has another object inside called "picture" that has 2 properties, key: string and url: string.

I want to make sure to also delete the file from storage when that object gets delete, I found this way that works, but I don't think it's the correct way to do it, specially because I get a TS Error:

"error TS2339: Property 'picture' does not exist on type '{}'."

Can anyone help me with that? Here is my delete method:

deleteEvent(id: string) {
        const obj = this.db.object(this.NODE + id);
        const getPic = obj.snapshotChanges().subscribe(
            (a) => {
                console.log(a.payload.val());
                this.storage.ref(this.NODE + a.payload.val().picture.key).delete();
            }
        );
        return obj.remove();
    }

1 Answer 1

1

I'd say you've got the gist of it. If the only thing that's bothering you is the Linting errors, you can use bracket notation instead of dot notation: this.NODE + a.payload.val()['picture']['key']... I might introduce some error handling in there in case things break.

On one hand, for a small improvement, I'd recommend against using a subscription just to get the data from the database one time. AngularFire2 has a method for that with less overhead setting up an observable/subscription, when it's just about to be deleted anyways. If I were doing it, I would write it something like:

deleteEvent(id: string)
{
    return this.db.database.ref(this.NODE + id).once('value').then( data => {
        console.log(data.val());
        return this.storage.ref(this.NODE + a.payload.val()['picture']['key']).delete().then( () => {
            console.log('Success!');
            return this.db.database.ref(this.NODE + id).remove();
        }).catch( err => {
            console.log(`Error deleting ${this.NODE + a.payload.val()['picture']['key']} from storage:`);
            console.log(err);
        });
    }).catch( err => {
        console.log(`Error obtaining /${this.NODE + id} from the database:`);
        console.log(err);
    });
}

*untested code

I'm a big fan of promises (as if you couldn't tell) and AngularFire2 uses them a lot - makes handling errors much easier.

Sign up to request clarification or add additional context in comments.

1 Comment

Hey @JeremyW bro thank you so much! I didn't know about the bracket notation. I actually love the approach you had, I'm becoming a fan of promises as well, it makes sense right? I just need to get a better hold of it. I really appreciate your help brother!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.