AngularJS:来自一个 $http 调用的两个承诺 [英] AngularJS: two promises from one $http call

查看:23
本文介绍了AngularJS:来自一个 $http 调用的两个承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道初始化/我从 AJAX 调用填充并在指令中的某处同时"使用的对象的最优雅方式是什么.

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;
})

我还使用了一个直接绑定到 var1 的指令:

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

var1 : '='

并且在指令内部对 var1 进行了一些检查.

and inside the directive there is some check on var1.

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

根据 (*1)、(*2) 中的哪一个先被调用,结果是不同的.

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

您对此案有何建议?如果我只将一个变量设置为 (*1),我将只使用 $http 获得的承诺.

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.

我想知道在 Angular 中最惯用的方法是什么.将 var1 和 var2 组合成一个对象对我来说似乎不太优雅.

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.

推荐答案

如果我没猜错 - 您想将异步接收的部分数据传递给指令,但您不想知道"接收到的数据结构的指令.

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.

然后您可以将数据请求移出控制器并使用服务(docsexamples) 作为附加层将处理数据请求并提供方法来提取 var1(或 var2)以直接在控制器内部使用(以及进一步在指令中使用).

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).

这篇关于AngularJS:来自一个 $http 调用的两个承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆