当将数据返回给控制器时,AngularJS工厂出现问题

3

我在将从API接收到的数据通过Angular发送到控制器时遇到了一些问题... 在代码中,您可以看到带有问题的注释... 我执行了一个 $http.get() 请求并获得了我的信息,但是然后,在返回中,数据消失了:S

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]

Ionic模板假信息具有以下结构:
// Some fake testing data
  var chats = [{
    id: 0,
    name: 'Ben Sparrow',
    lastText: 'You on your way?',
    face: 'img/ben.png'
  }, {
    id: 1,
    name: 'Max Lynx',
    lastText: 'Hey, it\'s me',
    face: 'img/max.png'
  }, {
    id: 2,
    name: 'Adam Bradleyson',
    lastText: 'I should buy a boat',
    face: 'img/adam.jpg'
  }, {
    id: 3,
    name: 'Perry Governor',
    lastText: 'Look at my mukluks!',
    face: 'img/perry.png'
  }, {
    id: 4,
    name: 'Mike Harrington',
    lastText: 'This is wicked good ice cream.',
    face: 'img/mike.png'
  }];

所以我想我需要把我的对象数组转换为那种类型...有人可以帮我吗!! 谢谢 :)

编辑过的!

还有一个问题...我该如何刷新数据。我读到工厂只会获取一次数据。但是当我添加一个新客户时,我需要重新加载新数据或有一个重新加载页面的按钮....我尝试使用 $state 但不起作用。

谢谢!

1个回答

3

这不是应该处理异步调用的方式。你应该等待它完成,然后从控制器返回数据。

在这种情况下,可以使用$q来实现。基本上,$http.get返回一个承诺。并在解决时执行.then第1个函数作为成功回调和第2个函数作为错误回调。

使用$q,您希望等待承诺完成。您可以使用$q.when(promise),它将再次具有.then函数,当promise对象得到解决并return一些数据时,.then函数将被调用。这个机制称为链式承诺

工厂

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

完美的解决方案!非常感谢Pankaj!! :)@stephen: 我认为不是。因为$http只有在控制器被调用时才会被调用(在我的情况下,在登录后)。 - user3088220
1
@JuanWilde,请查看更新的答案,其中包含更多解释...这将有助于您理解。谢谢 :) - Pankaj Parkar
1
好的。我不确定你的意图(客户列表是否会更改)。我假设你希望每次调用“all()”时都刷新它。 - stephen.vakil
@stephen.vakil 没问题,兄弟..谢谢你提醒我..这是可能的情况..再次感谢。 - Pankaj Parkar
1
佩服@Pankaj!我没有看到你的更新,现在我解决了$$promise返回数据的问题!:“DD +1! - user3088220
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接