为什么当数组中有 2 个项目时,Typescript 报告长度为 0


来自

Firestore onSnapshot 的响应是 2 条记录,我将其推送到一个名为 shop 的数组中。

this.db.collection("Countries").doc("AU")
    .collection("cPostcode").doc(this.searchby)
    .collection(this.shop).where(how, '==', true)
    .onSnapshot(function (querySnapshot) {
        querySnapshot.forEach(function (doc) {
            shop.push(doc.data());
        })
    });
    console.log('shop.length', shop.length, 'Shop', shop);
    if (shop.length) {
        this.shopList = shop; .........

我使用 shop.length > 0 来了解是否返回任何数据,但即使数组中有 2 个项目,shop.length 也等于 0。

控制台日志的输出显示length:2 -

shop.length 0 shop []
    0:{ABN: "1", ACN: "2"}
    1:{ABN: "3", ACN: "4"}
    length:2
    __proto__:Array(0)

我尝试在forEach中放置一个标志,但它超出了范围,我尝试的"this.count"变量也是如此。我已经断断续续地研究这个问题好几天了。我已经用谷歌搜索了这个问题和一般的打字稿帮助,但似乎没有其他人有这个问题。我做错了什么?

为了可靠地获得长度,您需要确保等待结果。

  this.db.collection("Countries").doc("AU")
    .collection("cPostcode").doc(this.searchby)
    .collection(this.shop).where(how, '==', true)
    .onSnapshot((querySnapshot) => {
        // In here, we have data
        querySnapshot.forEach((doc) => {
            shop.push(doc.data());
        });
        console.log('shop.length', shop.length, 'Shop', shop);
        // Therefore, shop.length should work _reliably_
        if (shop.length) {
            alert(shop.length);
        }
  });

替代方法包括使用 promise 或在获得结果时调用函数(而不仅仅是将所有代码放入该回调函数中(。

最新更新