AngularJS - controller doesn't get data from service when using $http

﹥>﹥吖頭↗ 提交于 2019-12-03 17:16:51

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!