【问题标题】:arrays in Ionic 3 local storageIonic 3 本地存储中的数组
【发布时间】:2018-01-05 09:33:09
【问题描述】:

我正在尝试通过使用 ionic 3 中的本地存储在 ionic 3 中实现购物车功能。我试图通过将产品的 id 存储在一个数组中并将其分配给本地存储中的一个键来实现这一点。我为此编写的代码如下:

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

但是在上面的代码中,每次只存储添加到数组的最后一个值。那么如何在本地存储中向数组添加新元素并保留以前的值。

【问题讨论】:

    标签: arrays typescript ionic2 local-storage ionic3


    【解决方案1】:

    您问题中的代码存在一些问题,导致其无法正常工作。它归结为异步操作的顺序,这里用 Promises 表示。

    基本上,then 回调中的所有内容都在方法中的其余代码之后执行。

    我用数字 0 - 6 表示了操作在逻辑上发生的顺序。

    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
    

    理解这一点的关键是要意识到一个promise解析或拒绝函数,我们传递给thencatch的函数是在Promise所代表的异步操作完成时执行的。

    Ionic 的Storage.getStorage.set 是基于Promise 的API,您需要正确组合它们以便操作以正确的顺序发生。新 id 确实被添加到 allBlogs 数组中,但之后它被持久化了。

    最简单、最优雅的方法是使用async/await

    你可以使用类似的东西

    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);
    }
    

    当我们使用async 函数时,代码的编排会发生变化,以便动作按照编写顺序进行编排,前提是await 使用在正确的位置。这是语法上的便利。

    如果您只想添加不存在的项目,您可以在插入之前使用Array.prototype.includes 检查是否存在。

    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);
    }
    

    【讨论】:

    • 您能否也请更新答案以确保该项目仅添加一次到数组中。您也很乐意解释我发布的代码中可能存在的问题。
    • 添加了解释,展示了原始代码如何乱序执行操作,并添加了一个示例,如果新值不存在,我们只添加它。
    【解决方案2】:

    在我看来,您正在将 allBlogs 初始化为一个空数组。

    我会尝试从本地存储中获取 if。 如果找不到,则初始化为空数组 一定要使用 let over var 来定义 allBlogs,但不要将其定义为空数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-19
      • 2016-09-03
      • 2018-03-27
      • 2020-01-23
      • 2018-04-23
      • 2015-11-02
      • 1970-01-01
      • 2020-12-31
      相关资源
      最近更新 更多