javascript - Angular:在 AJAX 成功时设置变量

标签 javascript jquery ajax angular request

我正在开发一个小应用程序并且一直在玩转 Angular。单击我正在调用 ajax get 请求的按钮时,我遇到了这个问题。在 ajax 成功时,我想将一个变量设置为给定的结果。但问题是变量没有被设置。我的代码如下...

export class HomePageComponent implements OnInit {
apiEndpoint = "myapiendpoint";
searchQuery = "";
searchResult = {};

constructor() {}

onSearchSubmit(e) {
    e.preventDefault();
    let queryUrl = this.apiEndpoint + this.searchQuery;

    $.ajax({
      url: queryUrl,
      dataType: "json",
      method: "GET",
      success: function(res) {
        this.searchResult = res;
      },
      error: function() {
        console.log("Error");
      }
    });
  }

  ngOnInit() {}
}

当我尝试设置变量 searchResult 时,它没有设置,但是当我在控制台中直接在成功回调中记录响应时,它在控制台中为我提供了整个响应。我做错了什么?

谢谢

最佳答案

当您在函数中使用 this 关键字时,它将指向成功函数的作用域而不是外部作用域,因此它不会更新外部作用域变量。这个问题有两种解决方案

<强>1。使用箭头函数 :

 $.ajax({
      url: queryUrl,
      dataType: "json",
      method: "GET",
      success: (res)=>{
        this.searchResult = res;
      },
      error: function() {
        console.log("Error");
      }
    });
  }

因为箭头函数没有自己的作用域。箭头函数中的 this 始终指向外部函数。

<强>2。将外部 this 复制到其中一个变量中,然后使用该变量代替 this :

将外部函数中的 this 复制到一个变量中,然后在 ajax success 函数中使用该变量,在这种情况下 this 将指向正确的上下文

喜欢下面

export class HomePageComponent implements OnInit {
apiEndpoint = "myapiendpoint";
searchQuery = "";
searchResult = {};

var that=this; // Copied this into that  variable 
constructor() {}

onSearchSubmit(e) {
    e.preventDefault();
    let queryUrl = this.apiEndpoint + this.searchQuery;

    $.ajax({
      url: queryUrl,
      dataType: "json",
      method: "GET",
      success: function(res) {
        that.searchResult = res;// use that instead of this
      },
      error: function() {
        console.log("Error");
      }
    });
  }

  ngOnInit() {}
}

使用上述解决方案之一,它将解决您的问题

关于javascript - Angular:在 AJAX 成功时设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54876978/

相关文章:

javascript - 如何更新要点?

javascript - 单击按钮时验证表单

javascript - 如何在点击页面时保持事件链接点亮?

javascript - RequireJS 加载依赖不一致

jquery - 如何在 div 中显示图像,悬停在某些元素上?

ajax - 通过 XMLHttpRequest 将数据发布到 Node

php - 如何防止php超时、运行循环?不操纵 max_execution_time?

c# - jqGrid LINQ 和匿名类型

Javascript:在 Promise.all Map 函数中的每个请求后添加超时

javascript - 如何从浏览器内存中删除 Ajax 请求?