首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >向控制器返回数据时AngularJS工厂出现问题

向控制器返回数据时AngularJS工厂出现问题
EN

Stack Overflow用户
提问于 2015-12-01 18:39:17
回答 1查看 869关注 0票数 3

我有一些问题要把我的API接收到的数据用角度传送到我的控制器.在代码中,您可以看到问题的注释.我执行一个$http.get()请求,并得到我的信息,但在返回时,数据显示:S

代码语言:javascript
复制
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;
            }
        };
    });

我得到的是:

代码语言:javascript
复制
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模板假信息具有这样的estructure:

代码语言:javascript
复制
// 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试过了,但是不起作用。

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-12-01 18:45:29

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

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

使用$q,您希望等待承诺完成。您可以使用$q.when(promise),它将再次具有.then函数,在解析promise对象时调用.then函数,并对一些数据进行return。这种机制称为chain promise

工厂

代码语言:javascript
复制
.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;
        }
    };
});

控制器

代码语言:javascript
复制
//.then function will get call when ajax gets completed.
Customers.all().then(function(customers){
   console.log(customers)
})
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34027669

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档