2

I make this Customer service with $resource:

.factory('Customer', function($resource, apiURL){
    return $resource(apiURL+'customers/:id', { id: '@id' }, {
        'update': {method: 'PUT'}
    })
})

When I update the customer (that is a Instance of Customer service), and after the promise is resolved, the customer var is cleaned. Why?

$scope.customer = Customer.get({id: $stateParams.id}, function (){
    console.log($scope.customer) // Object {id: 1, name: 'John Doe', ...}
    $scope.customer.$update()
        .then(function () {
            console.log($scope.customer) // Object { status: true, $promise: Object, $resolved: true }
        })
});
Marcos Kubis
  • 485
  • 1
  • 4
  • 11

2 Answers2

1

When I update the customer (that is a Instance of Customer service), and after the promise is resolved, the customer var is cleaned. Why?

When the $update resolves it clears and updates the $resource object with the new data. Your server is returning empty data.

If you want to update without clearing the object, put the updated object in the second argument of the Customer.update method.

Customer.update({id: $stateParams.id}, $scope.customer);

Or modify your server to return the updated information.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
0

I've created a simple service with json-server (https://github.com/typicode/json-server) based on a JSON file:

{
  "customers": [
    {
      "id": 1,
      "name": "John Doe",
      "age": 25
    }
  ]
}

I also copy-pasted your code (the only change I did was to use 1 instead of $stateParams.id) and tested it with the above service and angular-resource v1.4.8. There was no such problem - both console logs showed exactly the same output. Maybe the issue is caused by server-side code? I can't think of any reason why this would not work in Angular (except for older version of angular-resource).

Update

Your PUT method on the service should not only update customer on the server, but also return the updated object. If it doesn't, your $scope.customer is substituted with empty object which is returned from the service.

PJDev
  • 951
  • 5
  • 20