Javascript 如何正确连锁角式HttpPomise
我有一个角度服务功能:Javascript 如何正确连锁角式HttpPomise,javascript,angularjs,Javascript,Angularjs,我有一个角度服务功能: service.getItemByID = function(id) { var hp = $http({method: "GET", url: "service/open/item/id", headers: {"token": $rootScope.user.token}, params: {"id": id}}); return hp; }; 我需要在发送返回值之前对
service.getItemByID = function(id) {
var hp = $http({method: "GET", url: "service/open/item/id",
headers: {"token": $rootScope.user.token},
params: {"id": id}});
return hp;
};
我需要在发送返回值之前对其进行操作,并且我希望保持HttpPromise结构的完整性,因为我的控制器代码是为了期望HttpPromise的成功和失败函数出现而编写的
我已将服务改写为如下所示:
service.getItemByID = function(id) {
var hp = $http({method: "GET", url: "service/open/item/id",
headers: {"token": $rootScope.user.token},
params: {"id": id}});
var newHP = hp.success(
function(data, status, headers, config) {
data.x = "test"; //TODO: add full manipulation
alert("success");
return hp;
});
return newHP;
};
无论我返回hp还是newHP,此代码都有效。我的问题是:
这是一种正确的HttpPromise链接形式吗?调用
。success
返回它被调用的延迟对象。它不会创建新对象。它所做的一切就是在延迟服务器上注册一个success
回调
您可以使用新引用,也可以保留旧引用:
service.getItemByID = function(id) {
var hp = $http({method: "GET", url: "service/open/item/id",
headers: {"token": $rootScope.user.token},
params: {"id": id}});
hp.success(
function(data, status, headers, config) {
data.x = "test"; //TODO: add full manipulation
alert("success");
return hp;
});
return hp;
};
如果愿意,可以将它们全部链接起来,并直接返回延迟对象:
service.getItemByID = function(id) {
return $http({
method: "GET",
url: "service/open/item/id",
headers: {"token": $rootScope.user.token},
params: {"id": id}
})
.success(function(data, status, headers, config) {
data.x = "test";
alert("success");
});
};
我还想把它们都锁起来。然而,该链实际上并没有返回任何内容。他将如何使用链接维护相同的成功/失败界面?@JohnTseng-
success
返回原始的延迟对象。然后,您可以进一步调用success
/error
/,然后
调用延迟返回的。@JosephSilber-如果getItemByID()
的使用者将再次调用success()
,则必须注册成功处理程序。由于不保证首先调用哪个,因此在“第二个”成功处理程序中可能未定义data.x
。因此,在这种情况下,hp与newHP具有相同的身份?@kamituel-延迟/承诺回调将按注册顺序调用,因此服务的回调将始终在消费者的回调之前调用。