1

I have data stored using custom keys. I want to return all data that starts with the id KEY- so I loop over all the data and storage and push the ones that match into an array. I can see that the data is being pushed into data[] but when I call getData() in my component it returns an empty array. What am I doing wrong?

storage.ts

getData(): any {
  this.storage.ready().then(() =>
  {
    let data = [];
    this.storage.forEach((value, key, index) =>
    {
      if (value.id.startsWith("KEY-")) {
        data.push(value);
        console.log(data);
      }
    });
    return data;
  });
}

component.ts

ionViewDidLoad() {
    this.data = this.storage.geData(); 
}

I've also tried this way

ionViewDidLoad() {
    this.storage.getData().then(data => console.log(data));
 }
2
  • 1
    It might be because the return statement is in the wrong place. I would think you need to move it down a line so it's just outside the closing function bracket. Commented Mar 19, 2018 at 16:00
  • Unfortunately you can't immediately use promise result or return data from it. What you can do is only return a promise, then you can use it anywhere as promise. Commented Mar 19, 2018 at 16:00

1 Answer 1

2

So just return a promise from your function then try to resolve data with this promise.

getData(): any {
  return this.storage.ready().then(() =>
  {
    let data = [];
    this.storage.forEach((value, key, index) =>
    {
      if (value.id.startsWith("KEY-")) {
        data.push(value);
        console.log(data);
      }
    });
    return data;
  });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.