AngularJS - 使用$时,控制器不从服务中获得的数据HTTP控制器、不从、数据、AngularJS

2023-09-13 03:33:10 作者:措手不及¢

我有简单的web应用程序,我想从JSON加载一些数据。目前的数据是我的服务,一切工作中很难codeD。

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.

当我改变我的服务从外部加载的JSON同一数据文件控制器呈现视图它得到了一些数据之前。

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.

这就是它看起来像现在:

function() {
var tripsService = function() {

var trips = [{ .... SOME DATA }];

this.getTrips = function() {
            return trips;
        };

};



angular.module('customersApp').service('tripsService', tripsService);
}());

使用$ 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);
}());

下面是我的Plunker:

Here is my Plunker:

plnkr

我能做些什么来改变呢?我读过一些关于添加resolve属性我routeProvider,但我没能解决问题!

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 !

更新:也许我的描述不是precise不够的,我一定要多学习一些有关处理的数据!从JSON数据应只加载一次,这样任何看法改变不会重新加载原始JSON文件。

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.

感谢

推荐答案

您已经了解的承诺:http://chariotsolutions.com/blog/post/angularjs-corner-using-promises-q-handle-asynchronous-calls/

在服务,你应该直接返回调用的诺言 $ HTTP - 服务:

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;
          });
    };

在控制器你必须再调用然后 -method从服务访问数据:

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;
        })
    }

下面是一个更新Plunker从一个工作示例: http://plnkr.co/edit/QEvKMtKvhf49uIpNu5h8?p=$p$pview

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