Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can still use the on success/error calls.</p> <p>The method you've highlighted returns a <a href="http://docs.angularjs.org/api/ng.%24q" rel="nofollow">"Promise"</a> object. A good thing about promises is that they are chainable.</p> <p>So say you wish to respond to a $http request error in your controller:</p> <pre><code>app.factory('myService', function($http) { return { getFoo: function() { return $http.get('foo.json').then(function(result) { return result.data; }); } } }); app.controller('MainCtrl', function($scope, myService) { //the clean and simple way $scope.foo = myService.getFoo().then(function(){ //Do something with successful response }, function(){ //Do something with unsuccessful response }); } </code></pre> <p><strong>NOTE: This following next section no longer holds true. Promises used in templates are no longer automatically resolved to its values when the promise resolves.</strong></p> <p>You should also understand why assigning <code>$scope.foo</code> works in your templates. AngularJS has a bit of magic that will resolve any promises to the object you need in a template. So while your template might reference <code>foo.bar</code> and the output will be correct, whats actually happening in the background is that the template is waiting for the promise to be fulfilled before rendering that part of the template.</p> <p>Also, another gotcha is to remember to return an rejected promise if you're handling the error somewhere up in the chain.</p> <p>For example:</p> <pre><code>app.factory('myService', function($http, $q) { return { getFoo: function() { return $http.get('foo.json').then(function(result) { return result.data; }, function(result){ //I'm doing something here to handle the error return $q.reject(result); }); } } }); app.controller('MainCtrl', function($scope, myService) { //the clean and simple way $scope.foo = myService.getFoo().then(function(){ //Do something with successful response }, function(){ //Do something with unsuccessful response }); } </code></pre> <p>If we didn't return a rejected promise in the service, the controller's 'success' code path will be run instead of the reject path.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload