javascript - Uncaught (in promise): TypeError: this.categoryMap.get is not a function
问题描述
我在函数中调用 Map 的函数(get、set、keys 等)时遇到问题。该地图是从 Firebase 查询返回的。
下面是我的示例代码:
categoryMap = new Map<Number, String>();
//called onInit.
loadList() {
this.firestore.firestore.collection('skillType').doc('content')
.get().then(res => {
this.categoryMap = res.data().list;
});
}
sampleFunction() {
//myMap is a dummy map that I took from internet.
var myMap = new Map();
myMap.set(0, 'dummy'); //the function can be called.
console.log(myMap.get(0)); //Can get output.
console.log(this.categoryMap.get(1)); //Get the error message as title
}
这是categoryMap
调用后loadList()
:
1: "Development & IT"
2: "Design & Creative"
3: "Accounting & Consulting"
4: "Translation & Language"
5: "Sales & Marketing"
6: "Sports & Fitness"
7: "Academic & Curricular"
8: "Culinary"
9: "Labor work"
值在那里,但为什么我不能调用任何函数来获取我的数据?
解决方案
这是一个承诺问题,问题是 loadList 会立即解决,您不必等待它完成。这是您需要使用 async/await 而不是 Promise 链接的地方。以下是如何解决此问题的示例,您可以根据需要将其集成到上述解决方案中。
let categoryMap = new Map<Number, String>();
const populateList = async() => {
const snapshot = await firestore.firestore.collection('skillType').doc('content').get()
categoryMap = snapshot.data().list
}
const sampleFunction = async() => {
// Only populate it when you need it if possible
// If not do in the onInit method
await populateList()
// Now the map is populated
console.log(categoryMap.get(1))
}
sampleFunction()
推荐阅读
- java - Groovy Eval 函数来评估 sql 查询的某些部分
- javascript - 使用 AngularJS 将 Google 登录添加到您的网站
- java - 在 Java 项目中使用 Kotlin 库作为依赖项
- android - android.support.constraint.ConstraintLayout 不能转换为 android.widget.RelativeLayout
- docker - docker exec 的默认用户是什么?
- join - 如何使用自定义字段名连接 cakephp 3.x 中的两个表?
- python - 使用 Python 将 Pandas 数据帧插入 SQL-Server - Jupyter Notebook
- php - 在服务器端获取soapenv:Header部分
- swift - Cocoa Swift:将主菜单连接到首选项窗口控制器并禁用属性检查器中的最小化等项目在 Xcode 中不起作用?
- dialogflow-es - 您如何编写发布到本地网络上 API 的 Google Action