3

I'm having some problems to send data received from my API with Angular to my controller... In the code you can see comments with the issue... I do a $http.get() request and I get my info, but then, in the return, data dissapear :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;
            }
        };
    });

Here is what I get:

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]

The Ionic template fake info has this estructure:

// 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'
  }];

So I supose that I need to convert my array of objects into that... Can anyone help me!! Thanks :)

EDITED!

And one question more... How can I do to refresh data. I read that factories only get data one time. But when I add a new customer I need to reload new data or have a button to reload page.... I tried with $state but doesn't work.

Thanks!

1 Answers1

3

This is not the way how you should deal with the asynchronous call. You should wait until that finishes and then return data from the controller.

In this case it can be achievable by using $q. Basically $http.get returns a promise. And on resolve it execute .then 1st function as success callback & 2nd as a error callback.

Using $q you wanted to wait until promise gets complete. You could use $q.when(promise) which will again have .then function, .then function gets called when the promise object gets resolved and return some data. This mechanism is called as chain promise.

Factory

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

Controller

//.then function will get call when ajax gets completed.
Customers.all().then(function(customers){
   console.log(customers)
})
Community
  • 1
  • 1
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • Will this invoke the http request every time you call `all()`? – stephen.vakil Dec 01 '15 at 18:59
  • Perfect solution!! Thanks a lot Pankaj!! :) @stephen: I think no. Because the $http is only called when the controller is invoked (in my case, after Login) –  Dec 01 '15 at 19:01
  • @stephen.vakil no way.. the way I added answer it wouldn't make another call..seems like OP wants that list once and stored as cache.. – Pankaj Parkar Dec 01 '15 at 19:02
  • 1
    @JuanWilde look at the updated answer with more explanation...will help you for understanding.. Thanks :) – Pankaj Parkar Dec 01 '15 at 19:02
  • 1
    OK. wasn't sure what you intended (whether customer list will be changing). I had assumed you would have wanted it refreshed each time you called `all()` – stephen.vakil Dec 01 '15 at 19:06
  • @stephen.vakil np bro..Thanks for heads up..It can be possible scenario.. Thanks once again. – Pankaj Parkar Dec 01 '15 at 19:07
  • 1
    Hats off @Pankaj!! I didn't see your update and now I solved to the $$promise returned data issue!! :"DD +1!! –  Dec 01 '15 at 20:52