从工厂返回数组 - AngluarJS

时间:2017-08-04 10:51:24

标签: javascript angularjs arrays http

我希望执行多个http.get请求,将这些值保存到数组中,然后从我的工厂服务返回此数组。

我的服务:

dashboardServices.factory('NexaService', ['$http', function($http, $scope, $route) {
    var factory = {};
   factory.getRoomDateRange = function() {
       var dataArray = [];
        dataArray.push($http.get(wsAddr+'urlOne'));
        dataArray.push($http.get(wsAddr+'urlTwo'));
        factory = dataArray;
        return factory;
   };
    return factory;
}]);

我的控制器:

 $scope.getDateRangeRoom = function() {
    NexaService.getRoomDateRange()
    .success(function (data) {
        $scope.records = data;
        conData = data;
        $scope.loaded = true;

       //logic

    .error(function (error) {
        $scope.loaded = true;
        $scope.error = true;
    });
  }; 

这导致错误:

angular.js:11358 TypeError: NexaService.getRoomDateRange(...).success is not a function

如果我只有一个如下所示的请求,则不会报告错误:

factory.getRoomDateRange= function(){  
    factory = $http.get(wsAddr+'urlOne');     
    return factory;
};

我对这段代码的主要目标是从多个请求中返回数据,如果可以在没有正确的数组的情况下执行此操作。

3 个答案:

答案 0 :(得分:0)

首先,您必须以相同的顺序注入字符串依赖项。

dashboardServices.factory('NexaService', ['$http', '$scope', '$route', function($http, $scope, $route) 

然后像这样修改工厂

dashboardServices.factory('NexaService', ['$http', '$scope', '$route', function($http, $scope, $route) {
    var factory = {};


    factory.getRoomDateRange = function() {
        var dataArray = [];
        dataArray.push($http.get(wsAddr + 'urlOne'));
        dataArray.push($http.get(wsAddr + 'urlTwo'));
        return dataArray;
    };
    return factory;
}]);

由于您的服务返回一个http请求使用$q.all数组,一次发送多个请求。记得也注入$q

使用then代替success来捕获回复。自角度版本1.4

以来,成功已被弃用
$scope.getDateRangeRoom = function() {
    $q.all(NexaService.getRoomDateRange())
        .then(function(response) {
            console.log(response[0].data) // 1st request response 
            console.log(response[1].data) // 2nd request response 
            $scope.loaded = true; 

        }, function(error) {
            $scope.loaded = true;
            $scope.error = true;
        });
}

答案 1 :(得分:0)

您需要返回一个包含所有承诺的承诺:

factory.getRoomDateRange = function () {
  return $q.all([$http.get(wsAddr+'urlOne'), $http.get(wsAddr+'urlTwo')])
}

然后在你的控制器中:

$scope.getDateRangeRoom = function() {
  NexaService.getRoomDateRange()
  .then(function (data) {
        $scope.records = data;
        conData = data;
        $scope.loaded = true;

       //logic
  })
  .catch(function (error) {
      $scope.loaded = true;
      $scope.error = true;
  });
}; 

答案 2 :(得分:0)

你可以回复承诺:

function getAll() {

  return $q.all(
    ['urlOne', 'urlTwo'].map(
      url => $http.get(wsAddr + url).then(r => r.data)
    )
  );
}

getAll()
  .then(list => console.log('list of values', list))