【问题标题】:Having problems with AngularJS Factory when return data to the controller将数据返回到控制器时出现 AngularJS Factory 问题
【发布时间】:2015-12-01 18:39:17
【问题描述】:

我在将使用 Angular 从我的 API 接收到的数据发送到我的控制器时遇到了一些问题...在代码中您可以看到存在问题的 cmets...我做了一个 $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 但不起作用。

谢谢!

【问题讨论】:

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


    【解决方案1】:

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

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

    使用$q 你想等到promise 完成。您可以使用$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)
    })
    

    【讨论】:

    • 每次调用all()时都会调用http请求吗?
    • 完美解决方案!!非常感谢潘卡杰!! :) @stephen:我认为没有。因为 $http 仅在调用控制器时调用(在我的情况下,在登录之后)
    • @JuanWilde 查看更新后的答案并提供更多解释......将帮助您理解......谢谢:)
    • 好的。不确定您的意图(客户列表是否会改变)。我以为您每次致电 all() 时都会希望它刷新
    • 脱帽致敬@Pankaj!!我没有看到你的更新,现在我解决了 $$promise 返回数据的问题!! :"DD +1!!
    猜你喜欢
    • 2014-06-20
    • 2015-11-15
    • 2018-12-18
    • 2018-08-05
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    相关资源
    最近更新 更多