AngularJS Promise : $resource GET example
A simple example using $resource().get() to discover its main advantage : the fact it returns directy the data instead of a promise (though you can still use callbacks if you have meaningful work to do beside getting your data)
by Jérôme Sengel
October 27, 2015
HTML
<script src="https://code.angularjs.org/1.2.1/angular-resource.min.js"></script>
<div ng-app="app">
<div ng-controller="PromiseCtrl">
<h2>$resource().get()</h2>
<h3>Example 1 : The data directly returned by $resource().get()</h3>
<p>{{example1}}</p>
<h3>Example 2 : Success callback with $promise and then()</h3>
<p>{{example2}}</p>
<h3>Example 3 : Error callback with $promise and then()</h3>
<p>{{example3}}</p>
<h3>Example 4 : Success callback inside the get()</h3>
<p>{{example4}}</p>
<h3>Example 5 : Error callback inside the get()</h3>
<p>{{example5}}</p>
</div>
</div>
JavaScript
angular.module('app', [ 'ngResource' ]).controller('PromiseCtrl', [ '$scope', '$resource', function($scope, $resource) {
var resource = $resource('/echo/json/:fakeOptionalParameter');
$scope.example1 = resource.get();
resource.get().$promise.then(function(value) {
$scope.example2 = value;
});
resource.get({
fakeOptionalParameter : '/error'
}).$promise.then(null, function(value) {
$scope.example3 = value.status;
});
resource.get(function(value) {
$scope.example4 = value;
});
resource.get({
fakeOptionalParameter : '/error'
}, function(value) {
}, function(httpResponse) {
$scope.example5 = httpResponse.status;
});
} ]);