简体   繁体   中英

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'CountryArr' of undefined

As i'm trying to push JSON into array it shows me the error ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'CountryArr' of undefined here is the code below.

CountryArr: any[] = [];
async ngOnInit() {
    await csc.getAllCountries().forEach(function (index) {
      this.CountryArr.push({ "value": index.id, "name": index.name }); //shows error here
    });

    //this.CountryArr.push({ "value": "0", "name": "-- Select Country --" }); //it works
    //this.CountryArr.push({ "value": "0", "name": "-- Select Countryasdadasd --" }); //it works
    console.log(this.CountryArr);
}

As i try using this

this.CountryArr.push({ "value": "0", "name": "-- Select Country --" });
this.CountryArr.push({ "value": "0", "name": "-- Select Countryasdadasd --" });

it works and shows me on console but inside the forEach it shows me the error.

There is not CountryArr is this object because the context got changed when you used function keyword inside forEach method. So you need to switch it over to arrow function instead. Arrow function doesn't create a new context(scope), so, every should be working now. Here is the details explanation of javascript context and how it works with normal functions and arrow functions.

CountryArr: any[] = [];
async ngOnInit() {
    await csc.getAllCountries().forEach((index) => {
      this.CountryArr.push({ "value": index.id, "name": index.name })
    });
    console.log(this.CountryArr);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM