gpt4 book ai didi

javascript - AngularJs调用多个服务函数: which is the best way to call multiple REST service on angularjs during the init step?

转载 作者:行者123 更新时间:2023-11-28 15:16:44 25 4
gpt4 key购买 nike

我有这个基础设施

[播放] <-REST-> [ Karaf ]

和这个 Controller

        $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 方法(称为 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) 不返回任何内容。

换句话说:在初始化步骤中调用 angularjs 上的多个 REST 服务的最佳方式是什么?

最佳答案

尝试使用$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)

});

并且你必须返回服务的 promise

像这样

$scope.getCommandsWithAck = function (node) {

return connectHttpService.getCommands(function (response) {

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

N:B:你必须在 Controller 中注入(inject) $q

关于javascript - AngularJs调用多个服务函数: which is the best way to call multiple REST service on angularjs during the init step?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33560586/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com