Angular / Typescript:从setTimeout函数内部调用函数

时间:2018-04-14 05:05:58

标签: javascript angular typescript

我试图从setTimeout()函数内部调用一个函数。我在下面尝试了所有,但没有运气。我不确定它是Angular问题还是普通的javascript问题。如果我调用alert()函数它正在工作,但是当我调用我的函数时,它不起作用。

投掷错误:this.getThreshold不是函数 要么 不能红色属性' getThreshold'

component.ts

  updateCount(inspection, rankName: string, rankPlusOrMinus: string)
    {
        inspection.rankName = rankName;
        inspection.rankPlusOrMinus = rankPlusOrMinus;
        this.inspectionService
            .update(inspection).then(function(res) {
              /*  setTimeout(() => {
                    this.getThreshold(rankName, rankAcount);
                });
                */

                /*setTimeout(()=>{    //<<<---    using ()=> syntax
                      this.getThreshold();
                 },300);*/
               /*  setTimeout(function(){ // normal function
                    this.inspectionService.getThreshold(); 
                }, 300) */

            /*      setTimeout(_=> {
                    //this.getThreshold();
                      this.inspectionService.getThreshold();
                  }, 300);*/
                setTimeout(
                        function(){
                            this.getThreshold();
                        }
                    , 350);
              })
              .catch(function(rej) {
                console.log(rej);
              });
    }

    getThreshold() {
        alert("123");
    }

service.ts

update(inspection: Inspection): Promise<Inspection> {
        const url = '/api/inspection/updatecount/';
        let rankName = inspection.rankName;
        return this.http
            .post(url, JSON.stringify(inspection), {headers: this.headers})
            .toPromise()
            .then(response => {
                //this.alertService.success(`Successfully created associate "${associate.name}"!`, true);
                let data = response.json();
                if (rankName='A') inspection.rankAcount = data.rankAcount;
                if (rankName='B') inspection.rankBcount = data.rankBcount;
                if (rankName='C') inspection.rankCcount = data.rankCcount;
                return response.json() as Inspection;
            })
            .catch(error => {
            });
    }

    getThreshold() {
        alert("123");
    }

1 个答案:

答案 0 :(得分:3)

函数中的this引用当前的调用上下文,而不是继承的调用上下文,因为您使用的是完整的function()而不是箭头函数。请尝试使用箭头函数,因为它们从父块继承this值:

this.inspectionService
  .update(inspection).then((res) => {
    // ...
    setTimeout(() => this.getThreshold(), 350);