【问题标题】:Array of Empty Objects vs Array of Objects - Firebase and Polymer空对象数组与对象数组 - Firebase 和 Polymer
【发布时间】:2018-01-27 01:02:03
【问题描述】:

我正在尝试使用 Polymer Shop 模板创建在线商店,将标准类别对象替换为 Firebase Cloud Firestore 中的对象。初始化数据库后,我尝试使用对象在抽屉菜单中显示类别列表。

这个顶级示例使用 Cloud Firestore。除了代码之外,您还可以通过屏幕截图查看在控制台记录 categoryList 时控制台打印出的内容。

Cloud Firestore Console Output

let categoryList = []
firebase.firestore().enablePersistence()
      .then(function() {
          // Initialize Cloud Firestore through firebase
      var db = firebase.firestore();

      db.collection("product-categories").where('active', '==', true)
        .get()
        .then(function(querySnapshot) {
            querySnapshot.forEach(function(doc) {
                    // doc.data() is never undefined for query doc snapshots
            categoryList.push(doc.data())
            });
          })
            .catch(function(error) {
                console.log("Error getting documents: ", error);
          });  
      });

这是原始 Polymer Shop 模板中的代码,以及显示 categoryList 打印到控制台时输出的屏幕截图。

Polymer Shop Template Console Output

(function() {
let categoryList = [
  {
    name: 'oils_and_tinctures',
    title: 'Oils and Tinctures'
  },
  {
    name: 'concentrates',
    title: 'Concentrates'
  },
  {
    name: 'Vape',
    title: 'Vape'
  },
  {
    name: 'topicals',
    title: 'Topicals'
  },
  {
    name: 'pet_products',
    title: 'Pet Products'
  }
];

似乎我需要一个空对象数组,然后填充这些对象。如何从 Firebase Cloudstore 获取数据以匹配原始模板数据的格式?

提前感谢任何人的帮助!

【问题讨论】:

    标签: javascript arrays firebase polymer google-cloud-firestore


    【解决方案1】:
    querySnapshot.forEach(function (doc) => {
        categoryList.push({ name: doc.name, title: doc.title }) 
    }).
    

    function CategoryData(name, title) {
        this.title = title;
        this.name = name;
    }
    
    querySnapshot.forEach(function (doc) => {
        categoryList.push(new CategoryData(doc.name, doc.title)) 
    })
    

    使用第二种方式,您可以定义您喜欢的任何结构。

    【讨论】:

    • 感谢您的帮助!这无疑使提取某些 Firebase 属性变得更加容易,但显然 Polymer 使用路径系统,而不是对象来表示数据。总的来说,它还与 Polymer 不使用脏检查并允许您将数据推送到数组然后将它们绑定到 DOM 元素这一事实有关。我不知道。我仍在试图弄清楚。不过感谢您的帮助!
    • 将数据推送到数组时,数组引用不会改变。这就是聚合物不通知的原因。如果你想观察绑定,观察array.splices。这将通知更改。
    猜你喜欢
    • 2015-11-13
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    • 2011-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多