AngularJS $ HTTP数据不正确返回 [英] AngularJS $http data not returning correctly

查看:153
本文介绍了AngularJS $ HTTP数据不正确返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想封装数据(通过JSON文件)使用一个工厂在我的控制器使用,虽然当我打电话的工厂,它的执行我的 $范围之前返回数据,导致空数组。

I'm trying to encapsulate data (via a JSON file) to be used across my controllers using a factory, though when I call the factory, it's executing my $scope before the data is returned, resulting in an empty array.

我希望能够首先得到的数据,那么,执行这回我的数据,例如我的 $范围声明:

I want to be able to get the data first, then, execute my $scope declarations which return my data, for example:

angular.module('myApp')
.factory('StoreProducts', function ($http) {

    var storeData = [];

    var promise = $http.get('/example.json')
    .success(function (data) {
        storeData = data;
    });

    return {
        promise: promise,
        setData: function(data) {
            storeData = data;
        },
        getData: function() {
            return storeData;
        }
    };
});

控制器:

angular.module('myApp')
.controller('StoreCtrl', function ($scope, $log, StoreProducts) {

    $scope.data = StoreProducts.getData();

    $log.log($scope.data);
});

JSON文件:

[
    {
        "productId": "1",
        "name": "Example 1",
        "price": "5.99"
    },
    {
        "productId": "2",
        "name": "Example 2",
        "price": "2.99"
    },
]

我想这是因为的getData()函数的范围是完全关闭,不过,我似乎认为并非如此。我在做什么的完全的错吗?

I'm thinking it's because the scope of the getData() function is completely off, though, I seem to think otherwise. What am I doing utterly wrong?

推荐答案

它通常做的方法是,你的数据函数返回一个承诺对象。从概念的角度来看,如果你处理像数据检索异步操作,的getData 不能(也不应该)简单的返回值,而是一个承诺。

The way it's usually done is that your data function returns a promise object. From conceptual standpoint if you deal with asynchronous operation like data retrieval, getData cannot (and should not) simply return the value, but rather a promise.

的基本思想是:

angular.module('myApp')
.factory('StoreProducts', function ($http) {
    // ... 
    return {
        // ...
        getData: function() {
            return $http.get('/example.json').then(function(response) {
                return response.data;
            });
        }
    };
});

您稍后控制器使用方法:

which you later use in controller:

StoreProducts.getData().then(function(data) {
    $scope.data = data;
});

当然,你可以添加缓存层,如果你不想询问每个的getData 呼叫服务器。如果缓存的值可用,则再次​​回归的诺言,但这次承诺立即解决,而不发出请求:

Of course you can add caching layer if you don't want to query server on each getData call. If cached value is available, then again return promise, but this time promise resolves immediately without making a request:

getData: function() {
    return storeData ? $q.when(storeData) : $http.get('/example.json').then(function(response) {
        storeData = response.data;
        return storeData;
    })
}

这篇关于AngularJS $ HTTP数据不正确返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆