Jamie
Jamie

Reputation: 321

how to return a value from a ajax promise

I have a method in my angular 1.5 controller, as shown below but I wanted to refactor the ajax call into the factory itself but I'm having problems with promises.. I'm trying to get to a point where in my controller I can just call the method like I've shown below. Is this possible? I'm trying to avoid having the ...success(function(...) in the controller code.

Any help much appreciated.

Trying to move to

vm.member = someFactory.getMember(vm.id);

Existing working controller code

vm.myMethod = myMethod;
...

function myMethod() {
    someFactory.getMember(vm.id).success(function(response) {
      vm.member = response;
    });
}

When I move the getMethod line into the factory the response is populated obviously but as soon as I come back to the controller, even with the return value from the factory being the response the result is undefined. I know this is because of promises but is there a design pattern I'm missing or a clean way of doing this. Using my currently approach my controller is littered with .success(function()...)

Many thanks!

Upvotes: 0

Views: 91

Answers (1)

Estus Flask
Estus Flask

Reputation: 222389

The procedure is called promise unwrapping.

Besides the fact that success is deprecated and should be replaced with then,

someFactory.getMember(vm.id).then(function(response) {
  var data = res.data;
  ...
});

it is totally ok to have this in controller.

The alternative to this pattern is to return self-filling object (something that ngResource $resource does):

function getMember(...) {
  var data = {};
  $http(...).then(function (response) {
    // considering that response data is JSON object,
    // it can replace existing data object
    angular.copy(data, response.data);
  });
  return data;
}

In this case controller can get a reference to the object instantly, and the bindings of object properties {{ vm.member.someProperty }} will be updated in view on response.

The pattern is limited to objects (and arrays), scalar values should be wrapped with objects.

Upvotes: 0

Related Questions