AngularJs调用多个服务函数:这是在init步骤期间在angularjs上调用多个REST服务的最佳方法?

时间:2015-11-06 06:14:16

标签: javascript angularjs

我有这个基础设施

[play]< -REST-> [karaf]

和这个控制器

        $scope.getPrototypes = function (node) {
            connectHttpService.getPrototypes(function (response) {

                $scope.prototypes = response;
            }, node);
        }

        $scope.getCommandsWithAck = function (node) {

            connectHttpService.getCommands(function (response) {

                $scope.commandsWithAck = response;

            },  node, true);
        }

        $scope.getCommandsWithoutAck = function (node) {

            connectHttpService.getCommands(function (response) {

                $scope.commandsWithoutAck = response;
            },  node, false);
        }

其中connectHttpService是服务

    function getCommands(successHandler, failHandler, nodeId, ack) {
        $http({
            method: 'GET',
                       ........MY ENDPOINT.........

            }
        }).success(function(response) {
            successHandler(response);
        }).error(function(response) {
            console.log("connectHttpService got an error response: " + JSON.stringify(response));
        })
    }

问题是我的init方法(名为thorugh ng-init

      $scope.initCommands = function () {

                $scope.currentNode = $stateParams.node;
                $scope.getPrototypes($scope.currentNode); //(1)
                $scope.getCommandsWithAck($scope.currentNode); //(2)
                $scope.getCommandsWithoutAck($scope.currentNode); //(3)
            }
        }

调用$scope.getCommandsWithoutAck但不返回。在服务器端(karaf),我看到了呼叫和响应。浏览器没有错误。

  • 如果我删除(1)或(2)它可以工作
  • 如果我改变(3)和(2)的位置,它可以工作,但只是因为(2)没有返回任何内容。

换句话说:这是在init步骤中在angularjs上调用多个REST服务的最佳方法吗?

1 个答案:

答案 0 :(得分:4)

尝试使用$q

喜欢这个

$scope.currentNode = $stateParams.node;
$q.all([

    $scope.getPrototypes($scope.currentNode), //(1)
    $scope.getCommandsWithAck($scope.currentNode), //(2)
    $scope.getCommandsWithoutAck($scope.currentNode) //(3)

]).then(function(result){

   console.log(result[0]);//(1)
   console.log(result[1]);//(2)
   console.log(result[2]);//(3)

});

你必须从服务中返回承诺

喜欢这个

$scope.getCommandsWithAck = function (node) {

         return   connectHttpService.getCommands(function (response) {

                $scope.commandsWithAck = response.data;
                return $scope.commandsWithAck; //to complete promise
            },  node, true);
        }

N:B :您必须在控制器中注入$ q