【问题标题】:Unable to use foreach method on Firebase fetch data无法在 Firebase 上使用 foreach 方法获取数据
【发布时间】:2017-04-26 21:58:15
【问题描述】:

我在获取 Firebase 数据时卡住了。如何读取 Firebase 对象?

像这样的键:-KYl7Q_gcndAPqFC2eCn 让我坚持去获取它。我怎么知道那个对象名称?

** 此提取用于公共博客。

// Initialize Firebase
var config = {
  apiKey: "foobarbaz",
  authDomain: "whatever.com",
  databaseURL: "foo.com",
  storageBucket: "bar.com",
  messagingSenderId: "1234567890000"
};
firebase.initializeApp(config);

firebase.database().ref("pelanggan").on('value', function(snapshot) {
  var pelanggan = snapshot.val();
  console.log(pelanggan);
  var div_senarai_pelanggan = document.getElementById('div_senarai_pelanggan');

  console.log(key);
  var html = "";
  html = '<ol>';
  pelanggan.foreach(a, function(key, value) {
    console.log(key);
  })
  html += '</ol>';
  div_senarai_pelanggan.innerHTML = html;

});

这是我的fiddle

【问题讨论】:

  • 我建议尽快更改您的 API 密钥,因为您现在已经在互联网上公开了它
  • @imjared:该配置中的 API 密钥 sn-p 只是标识一个项目,就像 URL 一样。事实上,所有这些都是可公开共享的:您需要与用户共享它,以确保他们可以访问您的应用程序。见Is it safe to expose Firebase apiKey to the public?

标签: javascript firebase firebase-realtime-database


【解决方案1】:

Firebase 以对象格式存储您的内容。您应该能够在您的 console.log() 通话中看到这一点。 forEach()a method specific to arrays 所以你不能在一个对象上调用它。您需要使用

迭代对象集合
Object.keys( pelanggan ).forEach( function( key ) {
    console.log( pelanggan[ key ] );
});

如果您想使用.forEach() 的变体,我建议您使用Lodash's implementation,那么您可以做您想做的事情

_.forEach( pelanggan, function( item ) {
    console.log( item );
});

【讨论】:

  • 如何更改我的 api 密钥?
猜你喜欢
  • 2020-08-31
  • 2019-07-08
  • 1970-01-01
  • 2021-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多