0

Uncaught TypeError: Object #<Object> has no method 'getInvoices' 当我调用this.getInvoicesajax.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?
            }
        });
     }
}
4

2 回答 2

5

检查你的范围。我相信当您调用它时,您实际上指的是 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);
        }
    });
 }
于 2013-09-25T15:41:08.677 回答
1

使用简短的打字稿函数语法,它默认捕获类上下文:

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

}

于 2013-09-27T12:55:40.917 回答