Ionic class array not accessable

I am developing an Ionic application, and in one of my pages I’ve defined an array (instanceStack) consisting of sets of structured data (product, see below). In the function (saveToStack) that’s used to push these sets of structured data, I can access the data in the array after it has been pushed. However, and this is the problem, if I want to access it again from a different method (logInstances), it shows up blank.

Here’s the code.

export class HomePage {

product = { name: '', code: '', quantity: 1, salesMessage: "", discountPercent: 0.00, discountCurrency: 0.00, price: 0, listID: "", saleDate: "", saleTime: "", isSale: true, locationID: ""};
instanceStack = [];

constructor(private loadingCtrl: LoadingController, private alertCtrl: AlertController, private navCtrl: NavController, private nativeStorage: NativeStorage, private barcode: BarcodeScanner, private dataService: DataProvider, private storageService: StorageProvider, private http: Http, private navParams: NavParams) {
setInterval(() => this.logInstances(), 1000);
}

private saveToStack(){
this.instanceStack.push(this.product);
console.log(this.instanceStack[0]['name']); //Can access just fine, it's printed to console as expected.
}

private logInstances(){
 console.log("Instance Stack Length: "+ this.instanceStack.length); //As more things are pushed to instanceStack, this increases.
 console.log(this.instanceStack[0]['name']); //Nothing gets printed (here's the problem)
}

What is the problem here? Why is nothing being printed to the console in the logInstances function?

Can you show us how logInstances() is being invoked?

In my constructor (not addes in the code above) I have a timer set to call the function every second.

Please add it, then.

Are you doing

setInterval(function() {
    this.logInstances();
}, 1000);

or

setInterval(() => {
    this.logInstances();
}, 1000);
1 Like

I’ve added it to the code. :slight_smile: