首页 > 解决方案 > 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"

值在那里,但为什么我不能调用任何函数来获取我的数据?

标签: javascriptangulartypescriptfirebasegoogle-cloud-firestore

解决方案


这是一个承诺问题,问题是 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()

推荐阅读