簡體   English   中英

Angular2:在回調函數內部調用其他函數

[英]Angular2: Calling other functions inside call back functions

我正在構建Angular2應用程序。 我在myService有一個異步函數deleteObject 它返回一個Promise。 我在Component中有另一個函數稱為refresh ,它刷新頁面。 我如何從Promise內部調用刷新。 這是我嘗試的:

export class AppComponent{

    refresh(){
        // refresh page here
    }

    delete(){
        this.myService.deleteObject(params).then(
           function(data){
             //this.refresh() doesn't work here.
        });
    }
}    

如果使用Typescript進行編碼,則可以使用粗箭頭功能 他們保持this環境下,你會期望。 所以更換

delete(){
        this.myService.deleteObject(params).then(
           function(data){
             //this.refresh() doesn't work here.
        });
}

有了這個:

delete(){
    this.myService.deleteObject(params).then(
            (data)=>{
                //this.refresh() should work here
            }
    );
}

這是一個上下文問題。 “ this”是指回調函數的上下文,可以是promise或類似的東西。 您真正想要的是對組件上下文的引用,您可以像這樣實現

delete(){
    var componentRef = this; // colloquially "that" or "self"
    this.myService.deleteObject(params).then(
       function(data){
         componentRef.refresh() // does work here.
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM