如何在 angularjs 工厂中使用 json 文件返回对象数组

How to return array of object use json file in angularjs factory?

本文关键字:文件 json 返回 对象 数组 angularjs 工厂      更新时间:2023-09-26

在这里,我为服务调用创建了示例,该示例工作正常 一个接一个地调用示例的链接。

喜欢这个:-

     JSONService.getJSON('file.json').then(function(data){
       $scope.languages = data;
  });
 JSONService.getJSON('file1.json').then(function(data){
       $scope.languages1 = data;
  });

我不想单独发送。 为什么,因为如果它只有两个三个调用意味着很好。我需要打100多个电话。那次我不能一个接一个地做。所以像这样尝试

      JSONService.getJSON('file.json,file1.json').then(function(data){
       $scope.languages = data[0];
       $scope.languages1 = data[1];
  });

在服务中使用拆分值并尝试逐个推送承诺并返回为数组它不起作用我不知道我在哪里犯了错误,任何人都可以在这方面帮助我。.

app.service('JSONService', function($http){  
   var data = [];
    return{
        getJSON: function(url){
          var parameter=url.split(',');
          for(var i=0; i< parameter.length; i++){
             $http.get(parameter[i])
                .then(function(response){
                    data.push(response);
                });
          }
          return data;
        }
    };
 });

示例 2 的链接不起作用

你需要

为此使用承诺。 这是您需要使用的服务

app.service('JSONService', function($http, $q){  
   var data = [];
    return{
        getJSON: function(url){
          var urls = url.split(','),
              promises = [];
          for(var i=0; i< urls.length; i++){
             var inPromise  = $http.get(urls[i])
                .then(function(response){
                    data.push(response.data);
                });
              promises.push(inPromise);
          }
        //return the promise from the $q.all, that makes sure, that all pushed promises are ready and return the chapters.
        return $q.all(promises).then(function () {
            return data;
        });
        }
    };
 });

还更新了您的 plnkr http://plnkr.co/edit/smMv9jPyMRNYX2AzAuRC?p=preview。这会将所有结果连接到一个数组对象languages

$q

这就是$q的目的。

app.service("JSONService", ["$http", "$q", function($http, $q){
    return {
        getJson: function(callback){
            _urls = ["data1.json", "data2.json", "data3.json"],
            _urlCalls = [],
            _data = [];
            angular.forEach(_urls, function(url) {
                _urlCalls.push($http.get(url));
            });
            $q.all(_urlCalls).then(
                function(results) {
                    results.forEach(function(e,i){
                        _data.push(e.data);
                    });
                    callback(_data);
                 },
                 function(errors) {},
                 function(updates) {}
            );
        }
    }
}]);

用法

从控制器。

JSONService.getJson(function(response){
    console.log(response);
}