-->

AngularJS - controller doesn't get data from s

2020-06-24 07:46发布

问题:

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:

plnkr

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

回答1:

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:

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

In the controller you have then to call the then-method to access the data from the service:

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

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



回答2:

If you want to load the view when you retrieved the content you indeed need a route resolve.

You can do that by.

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

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.