Angular Ionic中TypeScript将Firestore返回对象转为Map的报错问题
问题原因与解决方案
嘿,我来帮你搞定这个Firestore的类型问题~
为什么会出现这个错误?
Firestore里的Map类型字段,当你通过ds.data()读取回来的时候,并不会直接转换成JavaScript原生的Map实例,而是会被解析成一个普通的JavaScript对象(plain object)。所以你代码里的interested其实是个普通对象,它根本没有keys()这类Map专属的方法,自然会报错说interested.keys is not a function。
而且你提到的“是否需要转为JSON对象”其实没必要,因为ds.data()返回的已经是解析后的JS对象了,问题出在类型不是你预期的Map上。
两种解决方法,选你顺手的来:
方法1:把普通对象转换成原生Map
如果你确实想用Map的各种方法(比如keys()、has()、get()),可以用Object.entries()把普通对象转成键值对数组,再传入Map构造函数,得到真正的Map实例:
handler: data => { firebase.firestore().collection("categories").doc(`${data.name}`).get() .then((ds) => { if (!ds.exists){ console.log("No such category"); } else{ let data = ds.data(); // 先拿到普通对象,再转成Map let interestedObj = data["interested"]; let interested = new Map(Object.entries(interestedObj)); console.log(Array.from(interested.keys())); // 现在正常运行 console.log(interested); // 这时候就是Map实例了 } });
方法2:直接操作普通对象(不用转Map)
如果只是需要获取键、值或者键值对,其实不用转Map,直接用JavaScript原生的Object方法就能实现同样的效果:
handler: data => { firebase.firestore().collection("categories").doc(`${data.name}`).get() .then((ds) => { if (!ds.exists){ console.log("No such category"); } else{ let data = ds.data(); let interested = data["interested"]; // 用Object.keys获取所有键,效果和Map.keys()类似 console.log(Object.keys(interested)); // 用Object.values获取所有值 // console.log(Object.values(interested)); // 用Object.entries获取键值对数组,和Map.entries()类似 // console.log(Object.entries(interested)); console.log(interested); } });
这样两种方法都能解决你的问题,看你更习惯哪种写法啦~
内容的提问来源于stack exchange,提问作者arnihere
相关产品推荐
相关产品推荐

