【问题标题】:TypeError: val.set is not a function (JS Map())TypeError: val.set 不是函数 (JS Map())
【发布时间】:2020-05-30 20:36:42
【问题描述】:

我遇到了这个问题,我正在执行 val.set(key, value) 并在文件 vendor-es2015.js 中抛出类型错误 TypeError: val.set is not a function

代码(简体):

import { Storage } from '@ionic/storage';


map = new Map();

this.storage.set('sth', map);

this.storage.get('sth').then((val) => {
    val.set(key, value); //TypeError, returns { } insead of a map.
});

有趣的是,这在浏览器中运行良好,但是当它使用 Capacitor 编译到 Android 时,就会抛出这个错误。

tsconfig.json

"target": "es2015",
"lib": [
  "es2018",
  "dom"
]

【问题讨论】:

  • 您是否尝试调试以查看 val 是什么,如果不是您期望的 Map
  • @Bergi 哦,是的,我忘了提。我在浏览器中返回的不是 Map 对象,而是一个经典的空 {} 对象。
  • 我想知道设备上的离子存储是否不支持以某种方式存储地图?这甚至可能吗?
  • 似乎很可能。我不知道离子,但看看How do I persist a ES6 Map in localstorage (or elsewhere)?

标签: angular typescript ecmascript-6 ionic4 capacitor


【解决方案1】:

正如the documentation 所说:

存储仅适用于字符串。但是,存储 JSON Blob 很容易: 只需在调用 set 之前 JSON.stringify 对象,然后 JSON.parse 从 get 返回的值。有关详细信息,请参阅下面的示例。

可能看起来像这样(更新为help from Bergi):

const mapStr = JSON.stringify(Array.from(map.entries()));
this.storage.set('sth', mapStr);

this.storage.get('sth').then((val) => {
    const theMap = new Map(JSON.parse(val));
    theMap.set(key, value);
});

【讨论】:

猜你喜欢
  • 2021-12-03
  • 2020-08-02
  • 2016-06-19
  • 1970-01-01
  • 2020-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-11
相关资源
最近更新 更多