I’m having trouble creating a simple feed, similar to that of Facebook. I mainly need advice on the general way of doing it - for example, should I load the data from the site’s server using a http request and store the generated json data in an array within a service? Where should the http code be - in the service or in the controller? How would I get the data to appear as soon as it’s loaded (at the moment the data only appears once I change page and go back)?
I’m pretty confused about the best way to do this and I would appreciate any help in the matter. Is it possible for someone to type out a very simple example of a functioning feed?
Your $http call belongs in your service, as you have shown here.
However, you should probably make use of the promise returned by the $http service. Otherwise, your $scope.posts will always be initially bound to an undefined value. Since you expect it to eventually return a collection, you would at least want to return an empty array at the time of loading. But you would probably be better served by firing off the request at the time of assignment to $scope.posts.
Thanks very much for your help, Adrichman.
I’ve changed my service to how you advised, but now it comes up with more posts than expected, and none of the values in the array are there. For example, if I write:
Hi ady sorry to have only just seen this now.
It sounds like you are returning the data that you want. Could you clarify what is unexpected about this behavior? If you console.log those objects you can inspect them further. Alert can only show you strings.
Hi Adrichman,
No problem at all! I appreciate all help I can get.
The unexpected part of this is where the data doesn’t show up in the app. There are 3 posts that are returned from the server, but in the app there are 5 blank posts. When I output the data variable, it comes up with:
hi ady, because PostService.get returns a promise when invoked (because we are returning the promise $http call), you just need to delay the assignment of the value of $scope.posts until the promise resolves.