数组打字稿的范围

时间:2019-05-31 10:25:24

标签: angular typescript angular7

我无法在以下代码中访问(打印)address1数组和elements数组。 为什么会这样?
有其他替代方法吗? console.log(address1 [i]);没有显示数组元素,并且self.elements.length为零。 但它可以在httpRequest.onreadystatechange = function() {....}

内部使用
export class MapComponent implements OnInit {
  elements = [];
  headElements1 = ["tweetID", "tweet", "sentiment", "Location"];
  constructor() { }
  ngOnInit() {
    var address1 = [];
    var i;

    var searchURL = "http://..........";
    var httpRequest = new XMLHttpRequest();
    var self = this;
    // Fetches an API response from the topics API
    httpRequest.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            console.log("yes");
            var jsonObject = JSON.parse(this.responseText);
            var dataKey = Object.keys(jsonObject)[1];
            var emoji;

            for (var i = 0; i < jsonObject[dataKey].length; i++) {
                self.elements.push({
                    "id": jsonObject[dataKey][i]["id"], ł
         "tweetID": jsonObject[dataKey][i]["tweetID"],
                    "tweet": jsonObject[dataKey][i]["tweet"],
                    "location": jsonObject[dataKey][i]["location"],
                    "sentiment": emoji
                });

                address1.push(jsonObject[dataKey][i]["location"]);
            }
        }
        //Works here 
        for (i = 0; i < self.elements.length; i++) {
            console.log('outside ');
            console.log(address1[i]);
        }
    }
    //Not working here
    for (i = 0; i < self.elements.length; i++) {
        console.log('outside ');
        console.log(address1[i]);
    }

    httpRequest.open('GET', searchURL, true);
    console.log('Hellobolo');
    httpRequest.send();
}   }

0 个答案:

没有答案