简体   繁体   English

在Javascript函数中调用Typescript函数

[英]Call Typescript function in Javascript function

I am getting the error Uncaught TypeError: Object #<Object> has no method 'getInvoices' when I call this.getInvoices in the ajax.error result. 我收到错误Uncaught TypeError: Object #<Object> has no method 'getInvoices'当我打电话this.getInvoices在ajax.error结果。 How can I access the typescript function from there? 如何从那里访问打字稿功能?

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

check your scope. 检查您的范围。 I believe when you are calling this you're actually referring to the ajax object and not the class InvoicesController 我相信当您调用此命令时,您实际上是在指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);
        }
    });
 }

Use short typescript functions syntax, it captures class context by default: 使用简短的打字稿函数语法,默认情况下它捕获类上下文:

// 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