AngularJS/Restangular索引JSON数据提取

AngularJS/Restangular indexed JSON data extraction

本文关键字:数据 提取 JSON 索引 Restangular AngularJS      更新时间:2023-11-19

我有一个应用程序,它接受报价输入(纯度、重量、总量),并推送到$scope.quote:

// Controller action //
$scope.quote.push({ 
  total: ((($scope.karat * $scope.spot) * $scope.percentage) / 20) * $scope.estimatedWeight,
  karat: $scope.karat * 100,
  description: $scope.description,
  actualWeight: $scope.actualWeight,
  estimatedWeight: $scope.estimatedWeight,
  percent: $scope.percentage * 100,
  spot: $scope.spot
})

// Factory //
app.factory('quoteFactory', function() {
  var quote = [];
  var factory = {};
  factory.getQuote = function () {
return quote;
  };
return factory;
})

以及报价完成后的过账/保存

$scope.save = function() {
  var now = $scope.getDate();
      $scope.quote.push({
        createdOn: $scope.getDate()
      })
    Restangular.all('quote').post($scope.quote).then(function(quote){
      $location.path('#/scrap')
    }); 
  };

当试图访问列表或编辑的引用JSON时,由于JSON结构的原因,我无法访问所有需要的信息。

{
"0": {
    "total": 401.79040000000003,
    "karat": 74,
    "description": "Rings",
    "actualWeight": 12,
    "estimatedWeight": 11,
    "percent": 80,
    "spot": 1234
},
"1": {
    "total": 560.7296,
    "karat": 56.8,
    "description": "Test",
    "actualWeight": 22,
    "estimatedWeight": 20,
    "percent": 80,
    "spot": 1234
},
"2": {
    "total": 48.5625,
    "karat": 92.5,
    "description": "Testing",
    "actualWeight": 80,
    "estimatedWeight": 75,
    "percent": 70,
    "spot": 20
},
"3": {
    "createdOn": "2013-11-26T21:26:42.253Z"
},
"_id": {
    "$oid": "52951213e4b05f03172f14e7"
}
}

每个索引表示报价的一个行项目和createdOn信息。我想弄清楚的是,是否有一种方法可以访问所有行项目信息,而不必调用每个单独的索引?

我研究了一些lodash/underline,考虑过重组后端。。。不太确定从这里去哪里。

在github 上完成项目代码

由于没有太多关于后端如何工作或处理数据的详细信息,我认为问题在于生成JSON。

我要做的是改变Angular将数据发布到服务器的方式,例如:

保存功能:

$scope.save = function() {
  var url = 'http:127.0.0.1:3000/url/you/send/your/data/to',
      json = JSON.stringify($scope.quote);
  $http({
    method: 'POST',
    url: url,
    data: json,
    headers: {
      'Content-Type': 'application/json'
    }
  }).then(function(response) {
    $location.path('#/scrap');
  });
};

这将为您提供更多的控制,并确保您可以控制如何将数据转换为正确的JSON,在本例中使用JSON对象的.stringify()方法。

我从你的评论中看到,你关心索引;传统上,与服务器同步的对象具有属性id,该属性表示其数据库id而非客户端数组索引。这是一种很好的方法,可以使客户端上的模型数据在服务器端保持真实性。

有相当多的库可以帮助处理客户端,我建议——因为您已经在使用Angular了——阅读Angular Resource。

注意:如果您想用JSON.stringify()方法支持较旧的浏览器,请确保使用Crockford的JSON2.js