AngularJS:从一个的$ HTTP呼叫的两个诺言 [英] AngularJS: two promises from one $http call

查看:123
本文介绍了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.

我不知道什么是应该做它的角最惯用的方式。
结合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.

然后,你可以将数据请求了控制器和使用服务(适用的文档例子)作为将处理数据请求,并提供了一​​些方法来提取附加层 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天全站免登陆