Remove Object And Storage Angular Firebase
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();
}
Answer
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.
Related Questions
- → Make a Laravel collection into angular array (octobercms)
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → Angularjs not working inside laravel form
- → Analysis of Flux implementations
- → how to write react component to construct HTML DOM
- → angular ng-repeat and images in a row
- → Conditional BG Color on AngularJS
- → Should I 'use strict' for every single javascript function I write?
- → getting the correct record in Angular with a json feed and passed data
- → "Undefined is not a function" at .toBe fucntion
- → angularjs data binding issue
- → Angular / JavaScript auto hydrate an instance
- → Convert generic text string in json object into valid url using Angular