2017-07-29 99 views
1

我想通过在离子3中使用本地存储在离子3中实现购物车功能。我试图通过将产品的ID存储在一个数组中,并将其分配给本地的一个键存储。我写了这样做的代码如下:阵列在离子3本地存储

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

但在上面的代码添加到阵列只有最后一个值存储在每个time.so我怎么能在本地存储新元素添加到阵列与维护以前的值。

回答

2

您的问题中的代码有几个问题妨碍了它的工作。这归结于异步操作的排序,这里用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 

理解的关键,这是实现一个承诺解决或拒绝功能,我们通过thencatch功能由无极表示的异步操作完成时执行。

Ionic的Storage.getStorage.set是基于Promise的API,您需要将它们正确组合,以便操作按正确的顺序进行。新的ID确实被添加到allBlogs阵列中,但在之后被保存。

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

当我们使用async函数的代码编排被改变,这样的行为是在编写它们的顺序编排,您可以用的东西沿着

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

行,前提是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); 
} 
+0

您是否也可以更新答案以确保项目仅添加到阵列一次。另外,你也可以非常友好地解释我发布的代码中可能存在的问题。 – OshoParth

+0

添加了一个解释,显示原始代码如何执行不按顺序的操作,并添加了一个示例,如果该值不存在,我们只添加新值。 –

1

对我来说,它看起来像你正在初始化allBlogs到一个空的数组。

我会做一些尝试,如果从本地存储。 如果未找到,则初始化为空数组 使用let over var通过所有方法定义allBlog,但不将其定义为空数组。

+0

似乎没有工作。 – OshoParth