首页 > 解决方案 > 在ajax调用之外访问数组?

问题描述

全部!我有一个 ajax 调用来获取 API 的结果。当我尝试在调用之外访问该数组时,它是空白的。帮助?

在下面的代码中,我获取属性列表,然后将结果分配给“mlsArray”变量。当我在 main 中控制台记录它时,我得到了想要的结果。

但是,如果我稍后调用 getHomes,则该数组为空。

main(auth) {
$.ajax({async: false,
    url: "https://api.simplyrets.com/properties? 
limit=500&lastId=0&status=active&maxprice=" +
    this.maximum + "&type=residential",
    type: 'GET',
    dataType: 'json',
    // authorize with the API credentials
    beforeSend: function(xhr) {
        xhr.setRequestHeader("Authorization", "Basic  " + auth);
    },
    success: function(res) {
     this.mlsArray  = Object.assign([], res);
     console.log(this.mlsArray);
    }
  });
}

 getHomes() {
  console.log(this.mlsArray);
 }
}

标签: javascriptangular

解决方案


您在这里处理的是javascript this“范围”规则。函数的上下文(默认情况下)采用调用它的对象的上下文(参见:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this )。

当你调用函数success时,你需要在函数中找到你想要bind的上下文:

success: function (res) {
 // do things ...
}.bind(this)

祝你好运!


推荐阅读