簡體   English   中英

在Javascript函數中調用Typescript函數

[英]Call Typescript function in Javascript function

我收到錯誤Uncaught TypeError: Object #<Object> has no method 'getInvoices'當我打電話this.getInvoices在ajax.error結果。 如何從那里訪問打字稿功能?

// Typescript
class InvoicesController {
     ...

     public getInvoices(skip: number, take: number): void {
         ...    
     }

     public createInvoice() {
          $.ajax({
            ...
            contentType: 'application/json',
            type: 'POST',
            success: function (res) {
                if (res.result === 'ok') {
                    this.getInvoices(0,100); // THIS DOES NOT WORK? 
                }
            },
            error: function (err) {
                this.getInvoices(0,100); // THIS DOES NOT WORK?
            }
        });
     }
}

檢查您的范圍。 我相信當您調用此命令時,您實際上是在指ajax對象,而不是InvoicesController類

public createInvoice() {
      me = this;
      $.ajax({
         ....
        contentType: 'application/json',
        type: 'POST',
        success: function (res) {
            if (res.result === 'ok') {
                console.log('Data saved1');

            }
            else {
                console.log('Save error1');
            }
        },
        error: function (err) {
            me.getInvoices(100,0); // TRY THIS

            console.log("error2"+err);
        }
    });
 }

使用簡短的打字稿函數語法,默認情況下它捕獲類上下文:

// Typescript
class InvoicesController {
 ...

 public getInvoices(skip: number, take: number): void {
     ...    
 }

 public createInvoice() {
      $.ajax({
        ...
        contentType: 'application/json',
        type: 'POST',
        success: (res) => {
            if (res.result === 'ok') {
                this.getInvoices(0,100); // WORK NOW 
            }
        },
        error: (err) => {
            this.getInvoices(0,100); // WORK NOW
        }
    });
 }

}

暫無
暫無

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

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