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) {

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

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(“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()
getEmpresas() {
return new Promise((resolve,reject) => {
this.empresas = ;
(response) => {
this.empresas = JSON.parse(data["_body"]);
console.log(“aaa”+this.empresas.length); // Prints 1 correctly
(error) => {
console.log(“this is the error”,error);