简体   繁体   中英

arrays in Ionic 3 local storage

I am trying to implement cart functionality in ionic 3 by using local storage in ionic 3. I am trying to do this by storing the id's of products in an array and assign it to a key in local storage. The code I wrote to do this is as follows:

var allBlogs = [];
this.storage.get('products').then((val) => { 
console.log(val + " = previous value")
allBlogs.push(val)});
allBlogs.push(this.navParams.get('id')) ;
console.log(allBlogs);
this.storage.set('products', allBlogs);

But in the above code only the last value added to array is stored each time.so how can I add new elements to the array in local storage with preserving the previous values.

There are a few issues with the code in your question that prevent it from working. It comes down to the ordering of asynchronous operations, here represented by Promises.

Essentially, everything inside of the then callback is executed after the rest of the code in the method.

I have indicated with the numbers 0 - 6 the order in which the operations logically happen.

var allBlogs = []; // 0
this.storage.get('products').then((val) => { // 1
  console.log(val + " = previous value"); // 5
  allBlogs.push(val); // 6
});
allBlogs.push(this.navParams.get('id')); // 2
console.log(allBlogs); // 3
this.storage.set('products', allBlogs); // 4

The key to understanding this is to realize that a promises resolution or rejection function, the function we pass to then or catch is executed when the asynchronous operation represented by the Promise completes.

Ionic's Storage.get and Storage.set are Promise based APIs, you need to compose them correctly so that the operations occur in the right order. The new id was indeed being added to the allBlogs array but after it was persisted.

The easiest and most elegant way to do that is by using async / await .

You can use something along the lines of

const key = 'products';

constructor(readonly storage: Storage, navParams: NavParams) {
  const {id} = navParams.data;
  this.updateStorage(id).catch(reason => console.error(reason));
}

async updateStorage(newId) {, f
  const storedIds = await this.storage.get(key) || [];
  const updatedIds = [...storedIds, newId];
  await this.storage.set(key, updatedIds);
}

When we use an async function the orchestration of code is altered so that actions are orchestrated in the order in which they are written, provided that await is used in the correct positions. This is a syntactic convenience.

If you only want to add an item if it does not already exist, you can use Array.prototype.includes to check for existence prior to insertion.

async ensureId(id) {
  const storedIds = await this.storage.get(key) || [];
  if (storedIds.includes(id)) {
    return;
  }
  const updatedIds = [...storedIds, id];
  await this.storage.set(key, updatedIds);
}

To me it looks like you are initializing allBlogs to an empty array.

I'd do something like try and get if from local storage. If not found then initialize to an empty array use a let over var to define allBlogs by all means but don't define it as an empty array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM