Difference between revisions of "$resource"

From Wiki2
(Created page with "As of Angular 1.2, resources support promises. But they didn't change the rest of the behavior. To leverage promises with $resource, you need to use the $promise property on ...")
 
 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
====[http://stackoverflow.com/questions/13269882/angularjs-resource-restful-example $resource restful]====
As of Angular 1.2, resources support promises. But they didn't change the rest of the behavior.
As of Angular 1.2, resources support promises. But they didn't change the rest of the behavior.


Line 4: Line 6:


Example using promises
Example using promises
<code>
<pre>
var Todo = $resource('/api/1/todo/:id');
var Todo = $resource('/api/1/todo/:id');


Line 20: Line 22:
   // fail
   // fail
});
});
</code>
</pre>
Just keep in mind that the $promise property is a property on the same values it was returning above. So you can get weird:
Just keep in mind that the $promise property is a property on the same values it was returning above. So you can get weird:


These are equivalent
These are equivalent
 
<pre>
var todo = Todo.get({id: 123}, function() {
var todo = Todo.get({id: 123}, function() {
   $scope.todo = todo;
   $scope.todo = todo;
Line 41: Line 43:
   $scope.todo = todo;
   $scope.todo = todo;
});
});
</pre>

Latest revision as of 18:44, 30 March 2014

$resource restful

As of Angular 1.2, resources support promises. But they didn't change the rest of the behavior.

To leverage promises with $resource, you need to use the $promise property on the returned value.

Example using promises

var Todo = $resource('/api/1/todo/:id');

Todo.get({id: 123}).$promise.then(function(todo) {
   // success
   $scope.todos = todos;
}, function(errResponse) {
   // fail
});

Todo.query().$promise.then(function(todos) {
   // success
   $scope.todos = todos;
}, function(errResponse) {
   // fail
});

Just keep in mind that the $promise property is a property on the same values it was returning above. So you can get weird:

These are equivalent

var todo = Todo.get({id: 123}, function() {
   $scope.todo = todo;
});

Todo.get({id: 123}, function(todo) {
   $scope.todo = todo;
});

Todo.get({id: 123}).$promise.then(function(todo) {
   $scope.todo = todo;
});

var todo = Todo.get({id: 123});
todo.$promise.then(function() {
   $scope.todo = todo;
});