16

EDIT

The first answer is the elegant one, but, as stated a few times in this question and another questions on stackoverflow, the problem is that the service and the controller run their thing before the data actually arrives.

(Last comment on the first answer:)

Yes, the problem is that the API calls finish AFTER the service runs and returns everything to the controller, see here screencast.com/t/uRKMZ1IgGpb7 ... That's my BASE question, how could I wait on all the parts for the data to arrive?

It's like I'm saying it on repeat, how do we make a service that populates the array after the successful data retrieval, and the controller getting data after all this happens, because as you can see in my screenshot, things run in a different order.


I have this code:

 var deferred = $q.defer();
            $http.get('../wordpress/api/core/get_category_posts/?category_id=14 ').success(function(data) {
                //we're emptying the array on every call
                theData = [];
                catName = data.category.slug;
                theData = data;
                theData.name = catName;
                aggregatedData.push(theData);
            });
            $http.get('../wordpress/api/core/get_category_posts/?category_id=15 ').success(function(data) {
                theData = [];
                catName = data.category.slug;
                theData = data;
                theData.name = catName;
                aggregatedData.push(theData);
            });
            $http.get('../wordpress/api/core/get_category_posts/?category_id=16 ').success(function(data) {
                theData = [];
                catName = data.category.slug;
                theData = data;
                theData.name = catName;
                aggregatedData.push(theData);
            });
            $http.get('../wordpress/api/core/get_category_posts/?category_id=17 ').success(function(data) {
                theData = [];
                catName = data.category.slug;
                theData = data;
                theData.name = catName;
                aggregatedData.push(theData);
            });
            //deferred.resolve(aggregatedData);
            $timeout(function() {
                deferred.resolve(aggregatedData);
            }, 1000);
            /*//deferred.reject('There is a connection problem.');
            if (myservice._initialized) {
                $rootScope.$broadcast('postsList', deferred.promise);
            }*/
            //myservice._initialized = true;
            myservice = deferred.promise;
            return deferred.promise;

For the life of me I can't understand why do I have to put a timeout when passing the resulting array to defer ?

Shouldn't the principle be like, defer waits for the information to come and then returns the promise? What is the point of that 1 second there? From what I understand defer should be able to wait as long as needed for the API to return the result and the return the promised data.

I'm really confused, I've banged my head against the walls for the last two hours because I was not receiving any data in my controller, only when I put that timeout there.

Arthur Kovacs
  • 1,710
  • 2
  • 17
  • 24
  • Did you mean to put all `$http.get` return values into [`$q.all`](http://docs.angularjs.org/api/ng.$q)? – Steve Klösters Sep 07 '13 at 14:14
  • I am throwing all the outputed arrays in the aggregatedData so I can pass that object to $q defer. I want to understand what's actually hapenning, here's a jsFiddle, http://jsfiddle.net/tjnWQ/ .... How does the promise work here. – Arthur Kovacs Sep 07 '13 at 14:20
  • To be honest, I'm riddled with frustration. It's almost 6 weeks now I'm trying to get a handle on this Angular, I really like the idea, I understand bits and pieces, I have 3-4 mini apps working, but there are some gaping holes in my knowledge of this Angular framework that get in the way of making an actual usable product :). I gave in and spend a lot of money on this book http://www.packtpub.com/angularjs-web-application-development/book – Arthur Kovacs Sep 07 '13 at 14:45
  • "The first answer is the elegant one, "...What was the question? – George Mar 30 '14 at 02:11
  • Back then, I couldn't manage to grasp and use the concept of promises in Angular, and I found some misleading article on the internet where some guy actually used $timeout [somehow] with the concatenation of the return of multiple promises, long story short, it was a mess of ideas in my head, and @dluz in the answer below made everything clear. – Arthur Kovacs Mar 30 '14 at 07:48

2 Answers2

60

IMHO I think there's a much clever (and elegant) way to do this with $q.all.

Please take a look at the code below.

I am assuming that you want to return the data at once with all the results aggregated on a big array.

var myApp = angular.module('myApp', []);

myApp.factory('myService', function ($http, $q) {
    return {
        getAllData: function () {
            return $q.all([
                $http.get('../wordpress/api/core/get_category_posts/?category_id=14'),
                $http.get('../wordpress/api/core/get_category_posts/?category_id=15'),
                $http.get('../wordpress/api/core/get_category_posts/?category_id=16'),
                $http.get('../wordpress/api/core/get_category_posts/?category_id=17')
            ]).then(function (results) {
                var aggregatedData = [];
                angular.forEach(results, function (result) {
                    aggregatedData = aggregatedData.concat(result.data);
                });
                return aggregatedData;
            });
        }
    };
});

You can see above that the aggregatedData is only generated once all the async calls are completed via the $q.all.

You just need to include the service as dependency into one of your controllers, for example, and call the service like this myService.getAllData()

Let me know if you need a full working example and I can provide one! :)

starball
  • 20,030
  • 7
  • 43
  • 238
Denison Luz
  • 3,575
  • 23
  • 25
  • 14
    +1 for `$q.all`, And to be a bit more DRY: `[14, 15, 16, 17].map(function (id) { return $http.get('../wordpress/api/core/get_category_posts/?category_id=' + id); });` – plalx Sep 07 '13 at 15:39
  • yep! agree with _plalx_! just didn't want to confuse him with some sweetness extra code :) – Denison Luz Sep 07 '13 at 15:42
  • AWESOME! It certainly looks more elegant than mine :). And regarding to my headaches above: Should I assume that $q.all will wait for ALL the API calls to finish and then serve the data in the final array. Data which can be also waited for in the controller with .then() ? – Arthur Kovacs Sep 07 '13 at 16:29
  • I started that book, I'll burn through it several times, I'm going to keep on trying till I get it right :). – Arthur Kovacs Sep 07 '13 at 16:31
  • Yes, the problem is that the API calls finish AFTER the service runs and returns everything to the controller, see here http://screencast.com/t/uRKMZ1IgGpb7 ... That's my BASE question, how could I wait on all the parts for the data to arrive? – Arthur Kovacs Sep 07 '13 at 16:46
  • `.then()` should wait and put everything inside `aggregatedData` only when all the data is there, but it's running amok :) – Arthur Kovacs Sep 07 '13 at 16:51
  • 1
    _Arthur_, I have the same book - in fact I am lucky enough to personally know one of the authors (Peter Bacon) of the book here in London :) I really like the book. Take a look at pages 84 - 94 (especially page 91) and you will get a better idea about `$q.all`. Happy to help! – Denison Luz Sep 07 '13 at 18:07
11

The $http.get calls are async, but you aren't waiting until they are all completed before resolving the deferred. Here it works with the timeout simply because your are lucky that the calls have time to complete within 1 second, however this isin't reliable at all.

I will not reiterate a complete solution here, but have a look at my answer for another similar issue.

Community
  • 1
  • 1
plalx
  • 42,889
  • 6
  • 74
  • 90
  • I know, that's exactly what I was saying, that timeout is a prop used heavily in demos, not talking to real life API's. That's what I'm looking for, a way to wait and display the data on both sides (Service->Controller->View) – Arthur Kovacs Sep 07 '13 at 16:30
  • Hey plalx, can you please see the first answer and my comment, the code is much clean, but there is a timing issue http://screencast.com/t/uRKMZ1IgGpb7 - the data still arrives after. – Arthur Kovacs Sep 08 '13 at 07:12
  • @ArthurKovacs Could you create a fiddle with all the relevant code? – plalx Sep 08 '13 at 13:15
  • Hey Plalx, that's the point, I tried it before (another question here on ), with data that's coming from array there is no problem, but with a REAL endpoint on my machine I keep getting that problem. Nonetheless, I'll make a fiddle with the actual code snippets. In a few minutes – Arthur Kovacs Sep 08 '13 at 16:21
  • I'm thinking of playing with https://github.com/mgonto/restangular/blob/master/README.md Will try other things to. PLALX, I'll push my app online on heroku sometimes this evening hopefully, I'll come back with a link. – Arthur Kovacs Sep 08 '13 at 16:45
  • Oh My God ... I took another look at your code and compare it to mine, even if it didn't have the square braces [] I took a closer look. APPARENTLY there was a syntax error ... look at this http://screencast.com/t/9GkEPLBEa --------- Jesus! ... Now this is frustrating to find out :). the result should be wrapped ONCE in the [] ... I did it twice (once when $q.all begins and for the results too). I feel so stupid. Everything WORKS, data's coming through, IT'S POURING WITH POSTS through my API. PLALX ... THANKS A LOT! – Arthur Kovacs Sep 08 '13 at 21:47
  • The First Answer is the correct one but you took the time to make it clear to me. I thank you again. – Arthur Kovacs Sep 08 '13 at 21:51
  • @ArthurKovacs, I'm glad it's working ;)! Good luck with the rest! – plalx Sep 09 '13 at 01:13