繁体   English   中英

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

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

在这里,我创建了服务调用,它是由一个做工精细呼叫一个样本链接样本

像这样:-

     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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM