AngularJS: two promises from one $http call

三世轮回 提交于 2019-12-25 05:30:34

问题


I wonder what is the most elegant way to initialize/the objects that I fill from the AJAX call and are used 'concurrently' somewhere in a directive.

I have a controller with such snippet:

$scope.var1 = {};
$scope.var2 = {};
$http({
  url: "/httpService",
  method: "GET",
  params: {}
}).success(function(data, status) {
  $scope.var1 = data.some; // (*1)
  $scope.var2 = data.other;
})

I am also using a directive which binds directly to var1:

var1 : '='

and inside the directive there is some check on var1.

if (var1.prop) // (*2) {
   doSth();
}

Depending on which of (*1), (*2) gets called first, the outcome is different.

What is your advice for this case? In case I would only have one variable set at (*1) I would just use the promise got as a result of $http.

I wonder what's the most idiomatic way to do it in Angular. Combining var1 and var2 into one object seems not elegant to me.


回答1:


If I got you right - you want to pass part of the data received asynchronously to the directive, but you don't want the directive to 'know' about data structures received.

Then you could move data request out of the controller and use services (docs, examples) as an additional layer that will handle data request and provide methods to extract var1 (or var2) directly for usage inside controller (and further in directive).




回答2:


Make a function in your directive that gets the promise from the $http call. Give the function a callback that will do:

if (var1.prop) // (*2) {
  doSth();
}

By making that part of the callback you ensure that it wont be done until after the data has returned from the call.

You don't have two promises from one call. You have one promise and one call. Treat it as such.



来源:https://stackoverflow.com/questions/27989363/angularjs-two-promises-from-one-http-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!