首页 > 解决方案 > Angular:在 AJAX 成功时设置变量

问题描述

我正在开发一个小型应用程序,并且一直在玩 angular。单击我正在调用 ajax 获取请求的按钮时,我遇到了这个问题。在 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 它没有设置但是当我控制台直接在成功回调中记录响应时,它会在控制台中给我整个响应。我究竟做错了什么?

谢谢

标签: javascriptjqueryajaxangularrequest

解决方案


当您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 成功函数中使用该变量,在这种情况下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() {}
}

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


推荐阅读