AngularJS - controller not receiving data from service when using $ http

I have a simple web application where I like to load some data from json. For now, the data is hardcoded in my service and everything works.

When I change my service to load the same data from an external json file, the controller renders the view before it receives some data.

What now looks like:

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:

plnkr

What can I do to change this? I read something about adding a resolve property to my routeProvider, but I couldn't solve the problem!

Update: Maybe my description is not accurate enough and I need to know more about data processing! The data from the json should just be loaded once, so any view change does not reload the original json file.

thank

+3


source to share


2 answers


You should inquire about promises: http://chariotsolutions.com/blog/post/angularjs-corner-using-promises-q-handle-asynchronous-calls/

In the service, you should immediately revert to the promise of calling $http

-Service:

    this.getTrips = function() {
         return $http.get('trips.json').then(function (response) {
            trips = response.data;
            return trips;
          });
    };

      



In the controller, you must then call a method then

to access the data from the service:

    function init() {
        tripsService.getTrips().then(function(trips) {
          $scope.trips = trips;
        })
    }

      

Here is an updated Plunker with a working example: http://plnkr.co/edit/QEvKMtKvhf49uIpNu5h8?p=preview

+3


source


If you want to load the view when you got the content, you really need a route.

You can do it.

$routeProvider
.when("/someRoute", {
    templateUrl: "sometemplat.html",
    controller: "someController",
    resolve: {
        trips: function(tripsService){
            return tripsService.getTrips();
       }
   }
})

      



This will resolve the variable caused by travel to the controller.

you need to add rides depending on your controller.

And if all trip actions need to be filled with data from api.

0


source







All Articles