Angular 在同一类中调用函数不起作用,typescript

Angular 在同一类中调用函数不起作用,typescript,angular,typescript,Angular,Typescript,我是typescript新手,在调用同一类中的函数时遇到问题: 我有这样一个函数: createPost(url: String, data: any) { $.ajax({ url: url + "/" + GLOBAL.REGISTER_URL, type: "POST", data: data.serialize(), success: function() { console.log("success");

我是typescript新手,在调用同一类中的函数时遇到问题: 我有这样一个函数:

createPost(url: String, data: any) {
    $.ajax({
      url: url + "/" + GLOBAL.REGISTER_URL,
      type: "POST",
      data: data.serialize(),
      success: function() {
        console.log("success");
      },
      error: function(request, status, error) {
        console.log(request.responseText);
        console.log(status);
        console.log(error);
      }
    });
  }
我试着在这里称之为:

.on('success.form.bv', function(e) {
        $('#success_message').slideDown("slow"); // Do something ...
        $('#contact_form').data('bootstrapValidator').resetForm();

        // Prevent form submission
        e.preventDefault();

        // Get the form instance
        var $form = $(e.target);

        // Get the BootstrapValidator instance
        var bv = $form.data('bootstrapValidator');

        // XXX reassigning port for testing purposes only
        var result = "https://" + window.location.hostname + ":" + GLOBAL.PORT + "/" + GLOBAL.VERSION + "/rest" + GLOBAL.REGISTER_URL;

        this.createPost(result, $form);
      });
但这不起作用,每次单击按钮时,浏览器中都会出现错误:

错误类型错误:this.createPost不是函数堆栈跟踪:
../../../../src/app/register/register.component.ts/RegisterComponent.prototype.ngOnInit/不要对TypeScript使用
函数{}
。改为使用
()=>{}
,以便
引用保持有效

否则您必须使用
(function(){}).bind(this)
来保持
this

  .on('success.form.bv', (e) => {
    // ......
    this.createPost(result, $form);
  });

我认为你的问题在于范围。。我可以建议您尝试以下方式:

.on('success.form.bv',(e) => { //<-- use arrow func
        $('#success_message').slideDown("slow"); // Do something ...
        $('#contact_form').data('bootstrapValidator').resetForm();

        // Prevent form submission
        e.preventDefault();

        // Get the form instance
        var $form = $(e.target);

        // Get the BootstrapValidator instance
        var bv = $form.data('bootstrapValidator');

        // XXX reassigning port for testing purposes only
        var result = "https://" + window.location.hostname + ":" + GLOBAL.PORT + "/" + GLOBAL.VERSION + "/rest" + GLOBAL.REGISTER_URL;

        this.createPost(result, $form);
      });

由于闭包,您遇到了问题。通常情况下,键入脚本和角度调整会使这成为一个罕见的问题,但是……您使用的是jQuery

要修复:

改变

createPost(url: String, data: any) {...}

fat-arrow或lambda函数创建一个不会改变作用域的词汇表

…另一方面,为什么要将jQuery与Angular 2+一起使用?Angular在捕获和公开DOM API方面已经做了很多工作,这似乎是在攻击自己
并通过使用jQuery颠覆,故意使事情变得过于复杂。Angular的功能足以使jQuery完全不必要。

这是。。。jQuery?你所说的“这里”到底在哪里?你能展示你的整个类吗?你所指的类在哪里?function()正在改变这个类的范围。尝试使用箭头函数(e)=>{this.createPost(result$form)}我们正在将以前的项目转换为angular framework,之前我们正在使用jquery。
createPost(url: String, data: any) {...}
createPost = (url: String, data: any) => {...}