如何正确使用AngularJS中的HTTP.GET? (动态地)

时间:2015-07-23 15:44:37

标签: json angularjs

我创建它有一个服务,然后将它传递给我的控制器,问题是我有它只读取一个静态文件(1.json),现在我已经用多个json填充了这个文件夹,我想知道,我怎样才能将它们全部带入,并动态地进行此调用。

服务:

todoApp.factory('eventData', function($http, $q){
return {
    getEvent: function(){
        var deferred = $q.defer();

        $http({method: 'GET', url: '/data/phonebook/1'}).
            success(function (data, status, headers, config){
                deferred.resolve(data);
            }).
            error(function (data, status, headers, config){
                deferred.reject(status);
            });

            return deferred.promise;
    }
};
});

控制器:

todoApp.controller('FeederController',
function FeederController($scope, eventData) {
    eventData.getEvent().then(
        function(event){$scope.event = event;},
        function(statusCode) {console.log(statusCode)});
}

);

祝福

2 个答案:

答案 0 :(得分:1)

您需要参数化服务电话。在那里,您可以更改代码以处理1 => N次调用,而不是使用循环。

todoApp.factory('eventData', function($http, $q){
    return {
    getEvent: function(id){
    var deferred = $q.defer();

    $http({method: 'GET', url: '/data/phonebook/'+id}).
        success(function (data, status, headers, config){
            deferred.resolve(data);
        }).
        error(function (data, status, headers, config){
            deferred.reject(status);
        });

        return deferred.promise;
      }
    };
});

并且您的控制器变为

todoApp.controller('FeederController',
   function FeederController($scope, eventData) {
       $scope.events = [];
       for(var i=0; i<10; i++){
       eventData.getEvent(i).then(
           function(event){$scope.events.push(event);},
           function(statusCode) {console.log(statusCode)});
       }
      }
);

答案 1 :(得分:1)

使用.then()与.success()时保持一致是件好事。此外,您可以使用$ http.get()方法。

todoApp.factory('eventData', function($http, $q){
    return {
       getEvent: function(id){

          var deferred = $q.defer();

          $http.get('/data/phonebook/' + id).then(function(data) {
             deferred.resolve(data);
          }, function (data, status) {
             deferred.reject(status);
          });

          return deferred.promise;
       }
    };
});

然后,您可以通过传递您需要的ID来获取您选择的ID。

todoApp.controller('FeederController', 
   function FeederController($scope, eventData) {

   $scope.GetEvent = function(id) {
      eventData.getEvent(id).then(function(event){
         $scope.event = event;
      }, function(statusCode) {
       console.log(statusCode);
      });
   };
});

然后获取您想要的信息。