【问题标题】:AngularJs: How to call multiple json files to tables using http.getAngularJs:如何使用 http.get 将多个 json 文件调用到表中
【发布时间】:2015-08-26 17:34:08
【问题描述】:

我正在开发一个应该从两个 json 文件中过滤和整理数据的应用程序。该应用程序将有两个表,它们使用 ngRepeat myData 比较和对比这些数据。到目前为止,top table 已经在请求一个 json 文件了:

app.controller('tableTopController', function ($scope, $http) {
$http.get('first.json').success(function(response){
    $scope.myData = response; });

底部的表应该从我的第二个 json 文件中读取数据:second.json。

【问题讨论】:

    标签: javascript json angularjs http


    【解决方案1】:

    尝试使用$q.all() 解决两个promise 并在两者都成功时执行回调函数。有关详细信息,请参阅docs

    var promises = [];
    
    promises.push(getFirstJson());
    promises.push(getSecondJson());
    
    $q.all(promises).then(function (results) {
        var firstJson = results[0];
        var secondJson = results[1];
    });
    
    function getFirstJson() {
        return $http.get(...);
    }
    
    function getSecondJson() {
        return $http.get(...);
    }
    

    【讨论】:

      【解决方案2】:

      如果您想在获取第二个文件之前等待第一次调用完成,并且如果您想确保在比较和对比之前加载所有内容:

      app.controller('theController', function ($scope, $http) {
          $http.get('first.json').success(function(response){
              $scope.firstData = response; 
              $http.get('second.json').success(function(response1){
                  $scope.secondData = response1;
                  //add any other logic you need to do here to compare & contrast
                  //or add functions to $scope and call those functions from gui
              });
          });
      });
      

      或者,按顺序调用它们,但您需要确保在加载两者之前无法开始比较和对比:

      app.controller('theController', function ($scope, $http) {
          $http.get('first.json').success(function(response){
              $scope.firstData = response; 
          });
          $http.get('second.json').success(function(response1){
              $scope.secondData = response1;
          });
          //add any other logic you need in functions here to compare & contrast
          //and add those functions to $scope and call those functions from gui
          //only enabling once both firstData and secondData have content
      });
      

      【讨论】:

      • 但是如果我需要调用9个json文件呢?
      • @Anton 这不是问题所问的,您正在寻找的解决方案将取决于您需要调用该数据的方式的细节,但我的回答中的技术和 Lucas Ribeiro 的回答中的技术可能会引导您找到您正在寻找的答案;但是,如果没有,并且您在 SO 上找不到任何其他帮助来指导您找到解决方案,为什么不问另一个问题,详细说明您要实现的目标?
      • 我只是不想重复同样的问题,这个问题和我的很接近,而且你的回答非常有效,我正在考虑如何减少代码,并且认为可能存在某种方法
      • @Anton 你好像想发帖到Code Review
      猜你喜欢
      • 2013-05-31
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-04
      • 1970-01-01
      • 2016-03-30
      相关资源
      最近更新 更多