【问题标题】:Firestore Document Deletion IssueFirestore 文档删除问题
【发布时间】:2018-03-15 10:23:56
【问题描述】:

我正在使用 firestore,在那里我编写了一个服务代码来从其中一个集合中删除文档。

服务代码:

firestore.service.ts

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

主代码:

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');
    }

因此,当我使用上面的代码时,会执行删除,但是该部分无法调用已经存在于 BlankComponent 类中的 showToastr/closeEditModal 方法。

它给出了这个错误:

TypeError:无法读取未定义的属性“closeEditModal”。

showToastr 方法也出现同样的错误。

请帮忙

【问题讨论】:

    标签: javascript firebase angular5 google-cloud-firestore


    【解决方案1】:

    在回调函数内部,this 的含义会更改为该特定函数。这意味着在您的this.showToastr(...) 行中,this 指的是没有showToastr 方法的本地回调函数。

    最简单的解决方案是为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"); 
        }); 
    

    我建议您也阅读其中的一些内容,因为这个问题之前已经讨论过(而且比我做得更好):

    【讨论】:

      猜你喜欢
      • 2022-06-30
      • 1970-01-01
      • 2019-02-03
      • 1970-01-01
      • 1970-01-01
      • 2019-04-04
      • 2021-07-01
      • 2020-09-01
      • 2020-10-12
      相关资源
      最近更新 更多