【问题标题】:Uncaught (in promise): TypeError: this.categoryMap.get is not a functionUncaught (in promise): TypeError: this.categoryMap.get is not a function
【发布时间】:2021-03-10 02:27:04
【问题描述】:

我在我的函数中调用 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
}

这是调用loadList()后的categoryMap

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"

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

【问题讨论】:

    标签: javascript angular typescript firebase google-cloud-firestore


    【解决方案1】:

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

    【讨论】: