0

I'm working with firestore, where i've written a service code to delete the document from one of the collection.

Service Code:

firestore.service.ts

    deleteFromCollection(id: string){
        this.eventDoc = this.afs.doc(`bookings/${id}`);
        return this.eventDoc.delete();
    }

Main Code:

blank.component.ts

    deleteData(){
        let audio = new Audio();
        audio.src= "./assets/app/media/sound/to-the-point.mp3";
        audio.load();

        this._firestoreService.deleteFromCollection(this.eventToShow.id).
        then(function(){
           this.closeEditModal();
           audio.play(); 
           this.showToastr("Deletion Done Successfully"); 
        }).
        catch(function(error){
           this.closeEditModal();
           audio.play(); 
           this.showToastr("Deletion Error"); 
        });   
    }


    showToastr(msg){
        this.message = true;
        this.deletionMessage = msg;
        setTimeout(() => this.message = false, 5000);
    }

    closeEditModal(){
        $('#edit_modal').removeClass('show');
    }

So when i'm using the above code the deletion is performed, but then section is not able to call showToastr/closeEditModal method which already present in BlankComponent Class.

It's giving this error:

TypeError: Cannot read property 'closeEditModal' of undefined.

and same error for showToastr method.

Please Help

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441

1 Answers1

0

Inside of a callback function, the meaning of this changes to that specific function. This means that in your line this.showToastr(...), the this refers to the local callback function which doesn't have a showToastr method.

The simplest solution is to create a shadow variable for the correct value of this:

   var that = this;
   this._firestoreService.deleteFromCollection(this.eventToShow.id).
    then(function(){
       that.closeEditModal();
       audio.play(); 
       that.showToastr("Deletion Done Successfully"); 
    }).
    catch(function(error){
       that.closeEditModal();
       audio.play(); 
       that.showToastr("Deletion Error"); 
    }); 

I recommend that you read some of these too, since this problem has been covered before (and way better than I can):

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807