【问题标题】:How to store firebase response in a Json Array如何将 Firebase 响应存储在 Json 数组中
【发布时间】:2016-05-09 09:13:40
【问题描述】:

目前我有一个硬编码的 url 数组,用于接收 html 中的图像。

    $scope.product = {
    "images" : [
    {"image": "https://s3-us-west-2.amazonaws.com/s.cdpn.io/194929/colorburst-700x700.jpg"},
    {"image": "https://s3-us-west-2.amazonaws.com/s.cdpn.io/194929/colorburst-700x700.jpg"},
    {"image": "https://s3-us-west-2.amazonaws.com/s.cdpn.io/194929/colorburst-700x700.jpg"}

  ] };

我刚刚学会了如何从数据库中接收数据,但是如何将结果存储在 json 数组中,就像“$scope.product”中显示的那样

我目前正在通过

接收数据
// Get a reference to our posts
var ref = new Firebase("https://<database>.firebaseio.com/profile");
// Retrieve new posts as they are added to our database
ref.on("child_added", function(snapshot, prevChildKey) {
  var newPost = snapshot.val();
  debugger;
  console.log("The email is: " + newPost.email);
}); 

【问题讨论】:

    标签: javascript html firebase firebase-realtime-database


    【解决方案1】:

    请记住,javascript 数组和对象不是 JSON 数组和字典,尽管它们匹配得非常紧密。您似乎想在收到数据时根据数据创建一个 javascript 对象。

    根据您的代码,将其调整为类似这样的结构应该会产生类似于您所询问的结构:

    // Get a reference to our posts
    var ref = new Firebase("https://<database>.firebaseio.com/profile");
    // some place to store stuff
    var results = {
      'emails':[]
    };
    // Retrieve new posts as they are added to our database
    ref.on("child_added", function(snapshot, prevChildKey) {
      var newPost = snapshot.val();
      results.emails.push({
        'email':newPost.email
      });
    });
    

    将 javascript results 对象转换为 JSON 字符串非常简单:

    var json_string = JSON.stringify(results);
    

    有几种排列数据的方法。我只能提供已知元素的代码。

    【讨论】:

    • 谢谢!结构是正确的,但我怎样才能在 html 中访问这个对象。在 html 页面加载时,该对象似乎仍然为空。我在 html 中使用 ng-repeat,但似乎对象的填充发生得太晚了。您对如何确保填充对象有任何建议
    • @noobie212 我对 Angular 不是很熟悉,但似乎 this answer 可能有你想要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多