Why length equal to 0?

Hello, i am trying to implement searchbar with values from Json. When i try to print empresas.lenght it is 0 but I have values in the json, i’ve checked it.
If I print values inside the function getEmpresas it shows the correct value.

The value losts outside the function.

Thanks a lot!

empresas: any;

constructor(public navCtrl: NavController, public navParams: NavParams, public http: Http) {
this.initializeItems();
}

initializeItems() {
this.getEmpresas();
console.log(“aa”+this.empresas.length); // Print 0
}

getEmpresas(){
this.empresas = ;
this.http.get(“http://www.xxxxxxxxxxxx.com/empresas.php”).subscribe( data => {
this.empresas = JSON.parse(data["_body"]);
console.log(“aa”+this.empresas.length); // Prints 1 correctly
}, err =>{
console.log(err);
});
}

console.log(“aa”+this.empresas.lenght); // Prints 1 correctly

Check the ‘length’ spelling .

Thanks. I did, but still returning 0.

This may be occuring because of the lifecycle timings. You are firing a log on the constructor, what if you ran it on ngOnInit() or at a later lifecycle hook?

the function initializeItems() defined by you as above is working in asynchronously, so before getting getEmpresas() response, the next line of your code also executed along with it.
So define your function with async and await, to call it synchronously.

please try below code
async initializeItems() {
await this.getEmpresas()
console.log(“aa”+this.empresas.length);
}
getEmpresas() {
return new Promise((resolve,reject) => {
this.empresas = ;
this.http.get(‘http://www.xxxxxxxxxxx.com/empresas.php’)
.subscribe(
(response) => {
this.empresas = JSON.parse(data["_body"]);
console.log(“aaa”+this.empresas.length); // Prints 1 correctly
resolve(response);
},
(error) => {
console.log(“this is the error”,error);
reject(error);
}
)
})
}