我有这个基础设施
[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),我看到了呼叫和响应。浏览器没有错误。
换句话说:这是在init步骤中在angularjs上调用多个REST服务的最佳方法吗?
答案 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