WASM构建可选参数使用:Go WASM调用IndexedDB传keyPath参数报错如何解决
问题解决方法
你之前的几种传参写法都没有正确构造JS对象格式的参数,所以IndexedDB无法识别配置项:
- 直接传字符串字面量,JS侧接收到的是普通字符串而非配置对象
- 传JSON序列化后的字节数组,对应到JS侧是Uint8Array类型,也不符合参数要求
- 把多个参数拼接为单个字符串属于语法错误,完全无法被解析
正确实现步骤
- 构造符合要求的
createObjectStore配置参数,两种写法均可:
// 写法1:直接传入Go map,syscall/js会自动转换为JS对象 storeOptions := map[string]string{"keyPath": "id"} objectStore := result.Call("createObjectStore", "employee", storeOptions) // 写法2:显式创建JS对象赋值,兼容性更强 // storeOptions := js.Global().Get("Object").New() // storeOptions.Set("keyPath", "id") // objectStore := result.Call("createObjectStore", "employee", storeOptions)
- 修正
add方法的参数,不能直接传Go字符串,要构造对应JS对象:
// 写法1:用map构造 empData := map[string]interface{}{ "id": "00-01", "name": "Karam", "age": 19, "email": "kenny@planet.org", } objectStore.Call("add", empData) // 写法2:显式创建JS对象 // empData := js.Global().Get("Object").New() // empData.Set("id", "00-01") // empData.Set("name", "Karam") // empData.Set("age", 19) // empData.Set("email", "kenny@planet.org") // objectStore.Call("add", empData)
完整修改后的代码片段
var dbUpgrade js.Func var result, request js.Value dbUpgrade = js.FuncOf(func(this js.Value, args []js.Value) interface{} { defer dbUpgrade.Release() result = this.Get("result") // 构造存储配置对象 storeOptions := map[string]string{"keyPath": "id"} objectStore := result.Call("createObjectStore", "employee", storeOptions) // 构造要插入的数据对象 empData := map[string]interface{}{ "id": "00-01", "name": "Karam", "age": 19, "email": "kenny@planet.org", } objectStore.Call("add", empData) window.Call("alert", "First record posted.") return nil }) request.Set("onupgradeneeded", dbUpgrade)
内容的提问来源于stack exchange,提问作者Hasan A Yousef
相关产品推荐
相关产品推荐

