Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is a Plunk that does what you want: <a href="http://plnkr.co/edit/TTlbSv?p=preview">http://plnkr.co/edit/TTlbSv?p=preview</a></p> <p>The idea is that you work with promises directly and their "then" functions to manipulate and access the asynchronously returned responses.</p> <pre><code>app.factory('myService', function($http) { var myService = { async: function() { // $http returns a promise, which has a then function, which also returns a promise var promise = $http.get('test.json').then(function (response) { // The then function here is an opportunity to modify the response console.log(response); // The return value gets picked up by the then in the controller. return response.data; }); // Return the promise to the controller return promise; } }; return myService; }); app.controller('MainCtrl', function( myService,$scope) { // Call the async method and then do stuff with what is returned inside our own then function myService.async().then(function(d) { $scope.data = d; }); }); </code></pre> <p>Here is a slightly more complicated version that caches the request so you only make it first time (<a href="http://plnkr.co/edit/2yH1F4IMZlMS8QsV9rHv?p=preview">http://plnkr.co/edit/2yH1F4IMZlMS8QsV9rHv?p=preview</a>):</p> <pre><code>app.factory('myService', function($http) { var promise; var myService = { async: function() { if ( !promise ) { // $http returns a promise, which has a then function, which also returns a promise promise = $http.get('test.json').then(function (response) { // The then function here is an opportunity to modify the response console.log(response); // The return value gets picked up by the then in the controller. return response.data; }); } // Return the promise to the controller return promise; } }; return myService; }); app.controller('MainCtrl', function( myService,$scope) { $scope.clearData = function() { $scope.data = {}; }; $scope.getData = function() { // Call the async method and then do stuff with what is returned inside our own then function myService.async().then(function(d) { $scope.data = d; }); }; }); </code></pre>
 

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