将数据返回到控制器时,AngularJS Factory出现问题

时间:2015-12-01 18:39:17

标签: angularjs ionic-framework ionic factory angularjs-factory

我将使用Angular从我的API收到的数据发送到我的控制器时遇到一些问题...在代码中你可以看到有问题的评论......我做了一个$ http.get()请求我得到了我的信息,然后,在回报中,数据消失:S

void(void*)

这是我得到的:

angular.module('OurenApp.services', ['ngCookies'])

    .factory('Customers', function (CONFIG, $cookies, $http) {
        // Get Customers from API
        var customers = [];
        var req = {
            method: 'GET',
            url: CONFIG.APIURL + '/customers/' + $cookies.get('user_id') + '/' + $cookies.get('API_KEY'),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
        };
        $http(req).then(function successCallback(response) {
            // Set message and send data to the view
            //console.log(response.data.customers);
            customers = response.data.customers; // <- Here I have an array of Objects (each object is a customer)

        }, function errorCallback(err) {
            // Set error message
            console.log(err);

        })
        return {
            all: function () {
                console.log(customers); // <- Here I have an empty object ¿?¿?¿?
                return customers;
            },
            remove: function (customer) {
                customers.splice(customers.indexOf(customer), 1);
            },
            get: function (customerId) {
                for (var i = 0; i < customers.length; i++) {
                    if (customers[i].id === parseInt(customerId)) {
                        return customers[i];
                    }
                }
                return null;
            }
        };
    });

离子模板假信息具有以下结构:

customers: Array[21]
0: Object
1: Object
2: Object
3: Object
    edited: "2015-11-26T22:57:25+0100"
    id: 88
    location: "Servicio Técnico Oficial"
    name: "Makumba"
    pass: "olakase"
    phone: "600999222"
    seen: 1
    status: "En Curso"
    __proto__: Object
4: Object
5: Object
6: Object
7: Object
8: Object
9: Object
10: Object
11: Object
12: Object
13: Object
14: Object
15: Object
16: Object
17: Object
18: Object
19: Object
20: Object
length: 21
__proto__: Array[0]

所以我想说我需要将我的对象数组转换成...任何人都可以帮助我!!谢谢:))

EDITED!

还有一个问题......如何刷新数据呢?我读到工厂只获得一次数据。但是当我添加一个新客户时,我需要重新加载新数据或者有一个按钮来重新加载页面....我尝试使用$ state但是没有用。

谢谢!

1 个答案:

答案 0 :(得分:3)

这不是应该如何处理异步调用的方式。您应该等到完成后再从控制器返回数据。

在这种情况下,可以使用$q来实现。基本上$http.get会返回一个承诺。并且在解决它执行.then第一个功能作为成功回调&amp;第二次作为错误回调。

使用$q您希望等到承诺完成。你可以使用$q.when(promise)再次拥有.then函数,.then函数在promise对象被解析时被调用,return一些数据被调用。此机制称为chain promise

<强>工厂

.factory('Customers', function (CONFIG, $cookies, $http, $q) {
    // Get Customers from API
    var customers = [];
    var req = {
        method: 'GET',
        url: CONFIG.APIURL + '/customers/' + $cookies.get('user_id') + '/' + $cookies.get('API_KEY'),
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
    };
    //created promise object
    var promise = $http(req).then(function successCallback(response) {
        // Set message and send data to the view
        //console.log(response.data.customers);
        customers = response.data.customers; // <- Here I have an array of Objects (each object is a customer)
        return customers;
    }, function errorCallback(err) {
        // Set error message
        console.log(err);
        return err;
    })
    return {
        all: function () {
            console.log(customers); // <- Here I have an empty object ¿?¿?¿?
            //returned promise will wait till promise gets complete.
            return $q.when(promise).then(function(){
               return customers; //returning data to continue promise chain
            });
        },
        remove: function (customer) {
            customers.splice(customers.indexOf(customer), 1);
        },
        get: function (customerId) {
            for (var i = 0; i < customers.length; i++) {
                if (customers[i].id === parseInt(customerId)) {
                    return customers[i];
                }
            }
            return null;
        }
    };
});

<强>控制器

//.then function will get call when ajax gets completed.
Customers.all().then(function(customers){
   console.log(customers)
})