I have simple web app where I like to load some data from json. At the moment the data is hardcoded within my service and everything is working.
When I change my service to load the same data from an external json file the controller renders the view before it gets some data.
That's what it looks like now:
function() {
var tripsService = function() {
var trips = [{ .... SOME DATA }];
this.getTrips = function() {
return trips;
};
};
angular.module('customersApp').service('tripsService', tripsService);
}());
Using $http.get :
function() {
var tripsService = function() {
var trips = [];
this.getTrips = function() {
$http.get('trips.json').success(function (data) {
var trips = data;
return trips;
});
};
};
angular.module('customersApp').service('tripsService', tripsService);
}());
Here is my Plunker:
What can I do to change this ? I have read something about adding resolve property to my routeProvider but I wasn't able to solve the problem !
Update: Maybe my description wasn't precise enough and I have to learn some more about handling data ! The data from json should just load once, so that any view change wouldn't reload the original json file.
thanks
You have to learn about promises: http://chariotsolutions.com/blog/post/angularjs-corner-using-promises-q-handle-asynchronous-calls/
In the service you should return directly the promise of the call to the
$http
-Service:In the controller you have then to call the
then
-method to access the data from the service:Here is a updated Plunker with a working example: http://plnkr.co/edit/QEvKMtKvhf49uIpNu5h8?p=preview
If you want to load the view when you retrieved the content you indeed need a route resolve.
You can do that by.
This will resolve a variable called trips into the controller.
you need to add the trips to your controller dependencies.
And if everything works trips should be filled with the data from the api.