Promise on AngularJS resource save action Promise on AngularJS resource save action angularjs angularjs

Promise on AngularJS resource save action


There is two slightly different API's, one for working with a resource instance and - in lack of better words - more generic version. The main difference beeing the use of $-prefixed methods (get vs $get)

The $-prefixed methods in ngResource/resource.js. proxies the call and returns the promise directly.

AFAIK before the resource gets instanciated, you can only access resources with the normal get.

var promise = Resource.get().$promise;promise.then(function(res)  { console.log("success: ", res); });promise.catch(function(res) { console.log("error: ", res); });

With instanciated resource the $-prefixed methods are available:

var res = new Resource({foo: "bar"});res.$save()    .then(function(res)  { console.log("authenticated") })    .catch(function(req) { console.log("error saving obj"); })    .finally(function()  { console.log("always called") });


If you look at angular documentation on resource it mentions

It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data.

This may very well means that your call to $save would return empty reference. Also then is not available on Resource api before Angular 1.2 as resources are not promise based.

You should change your saveCourse method call to accept a function parameter for success and do the necessary action there.


This is for Angularjs 1.0.8

In my service I have the following:

angular.module('dataProvider', []).  factory('dataProvider', ['$resource','$q',function($resource,$q) { //....var Student = $resource('/app/student/:studentid',    {studentid:'@id'});    return {      newStudent:function(student){        var deferred = $q.defer();        var s = new Student({name:student.name,age:parseInt(student.age)});        s.$save(null,function(student){            deferred.resolve(student);        });        return deferred.promise;      }    };}]);

In my controller:

$scope.createStudent=function(){  dataProvider.newStudent($scope.newStudent).then(    function(data){      $scope.students.push(data);  });};