Hello, I am doing a dynamic select with angular, depending on the choice of a region, the countries that are displayed in the select will be.
I attach my code:
coutry: any[] = [{ cca3: "0", name: "Selecciona un país" }];
public frase: CountrySelect = { cca3: "", name: "" };
getCoutry() {
var region = this.defaultRegion;
this.dataStorageService.getCountryByRegion(region)
.subscribe(data => {
let cioc = "";
let nameCoutry = "";
for (let index = 0; index < data.length; index++) {
cioc = data[index]['cioc'];
nameCoutry = data[index]['name']['common'];
this.frase.name = nameCoutry;
this.frase.cca3 = cioc;
console.log(this.frase);
this.coutry.push(this.frase);
}
/* console.log(this.coutry); */
});
}
when I do the console.log of this.phrase it prints all the countries and their code fine , but somehow when I push the array and print it or see it in the application it prints the n countries of that region but all with the same name and code of the last data element
How can I solve this and be able to add the countries to the array correctly?
I hope you can help me
The problem occurs because the
frase
one being added to the arraycountry
always contains the same reference (position in memory) even if the value of its properties (cca3
andname
) changes.I leave some possible solutions in JavaScript (without Angular) that are the case.
Solution #1: Moving the declaration
You could move the following definition:
Inside the method
subscribe
.Solution #2: Using the spread operator
In this way, what we do is create a new copy of the object
frase
to include incountry
. In this case it makes no difference where the variable is definedfrase
.More info: https://es.javascript.info/object-copy