multiple $http with promise using factory, angular

倖福魔咒の 提交于 2019-12-08 23:16:38

Your service is not aware of your $scope out of the box, nor do you probably want it to be as the whole point of services is to assist with the modularity of your code.

What you probably want to do is actually return the $http promise from your service so that your .success() callback can actually set models on the $scope via closure (being inside the controller).

So your factory would be more like this:

.factory("getDefaults", function() {
  return {
    instructions: $http({ method: "GET", url: "/getStringDropdown/materials" })
  }
});

If you really think you'll never need those http calls separately and you only care about when they all resolve. You could return a $q.all() promise that will resolve when they all resolve:

.factory("getDefaults", function($http, $q) {
  var promise1 = $http({ method: "GET", url: "/getStringDropdown/materials" });
  var promise2 = $http({ method: "GET", url: "/getStringDropdown/materials" });
  var promise3 = $http({ method: "GET", url: "/getStringDropdown/materials" });
  return {
    data: $q.all([promise1,promise2,promise3]),
    anotherCall: $http.get('/anothercallUrl')
  }
});

So now from your controller you could just do:

function myCtrl($scope,getDefaults){
   getDefaults.data.then(function(data){
     //access all three of your promises, their data, and set $scope models here
     getDefaults.anotherCall.success(function(data){
       //or another http call
     });
   };
}

$q.all documentation here: https://docs.angularjs.org/api/ng/service/$q

Using scopes in factories is not a good idea , my suggestion to not use, about multiple http calls you should use $q.all

example here in fiddle

for each call you should create defered object push it into array then use

$q.all(deferesArray).then(
      function(resp){
         // all requests are resolver , resp is array with resolved datas
        }
  )

You may want to have a look at angular's q$ (https://docs.angularjs.org/api/ng/service/$q)

1.) Create the first three promises that must finish "first"

 var deferred = $q.defer();
$http({
    method: "GET",
    url: "/getStringDropdown/procedure"
})
.success(function(data, status, headers, config){
    deferred.resolve(data);
});
var promise1 = deferred.promise;

2.) Use all method of q$, then call a "then" to the result to execute the second part of your logic

q$.all([promise1, promise2, promise3])
.then(function(results) {
 $http({
    method: "GET",
    url: "/getSavedFormData/formID"
  })
  .success(function(data, status, headers, config){
    $scope.instructions.materials= data.materials;
    $scope.instructions.procedures = $scope.procedures[data.procedure];
    $scope.instructions.reinforce = $scope.reinfoce[data.reinforcement];
 });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!