3

I am trying to resolve a promise from angular $resource save.

The docs specify that I can access the raw $http promise via the $promise property on the object returned as follows:

var User = $resource('/user/:userId', {userId:'@id'});
User.get({userId:123})
    .$promise.then(function(user) {
      $scope.user = user;
    });

This works for the get, however, when I attempt to access the promise on the save, I get an error. What am I doing wrong and why would resolving the save work differently than resolving the get?

Note: The POST request is working and I can see the correct response being returned from the server in the browser's Network tool. I just can't access the results in the promise.

In My Service

var itemResource = $resource('/api/myUrl/:id/:action', { id: '@id', action: '@action' });

function getItem(id) {
    return itemResource.get({ id: id });
}

function saveItem(item) {
    return itemResource.save(item);
}

In My Controller

var getResult = itemService.getItem({ id: 1560 });
getResult.$promise.then(function (itemDef) { // THIS WORKS!!!
    console.log(itemDef);
});

var saveResult = itemService.saveItem(item);
saveResult.$promise.then(function (itemDef) { // Cannot read property 'then' of undefined
    console.log(itemDef);
});
Ben Ripley
  • 2,115
  • 21
  • 33
  • 1
    Can you create a demo? – dfsq Sep 14 '15 at 18:30
  • what angular version you use? – Grundy Sep 14 '15 at 18:51
  • @dfsq I'd create a plunkr but m not sure how to create one that I can POST to. If you have any ideas, let me know and I'll post an example. – Ben Ripley Sep 14 '15 at 18:54
  • 3
    Just use your code. It doesn't matter if request fails. You will anyway see if the code throws "Cannot read property 'then' of undefined" error. – dfsq Sep 14 '15 at 18:59
  • 2
    @BenRipley, you can change this [plunker](http://plnkr.co/edit/OLM0EE7zCELrst3k5E7e) here seems your code work ok and `saveItem` return object with property `$promise` – Grundy Sep 14 '15 at 19:00

1 Answers1

0

You need to call the then method on the save response directly:

var saveResult = itemService.saveItem(item);

saveResult.then(function(itemDef) { ... });
tbm
  • 1,142
  • 12
  • 22