javascript - How to correctly chain Angular HttpPomise -
i had angular service function:
service.getitembyid = function(id) { var hp = $http({method: "get", url: "service/open/item/id", headers: {"token": $rootscope.user.token}, params: {"id": id}}); return hp; };
i need manipulate returned values before sending them on , want keep httppromise structure intact since controller code written expect success , failure functions of httppromise present.
i have rewritten service this:
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; };
this code works , work regardless of whether return hp or newhp. question is: proper form of httppromise chaining?
calling .success
returns same deferred object called on. not create new object. register success
callback on deferred.
you can use new reference, or keep old reference:
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; };
if want to, chain them all, , return deferred object directly:
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"); }); };
Comments
Post a Comment