Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

Sorry I am new to Angular. And this is probably dump question. I have following data structure in a json:

[
    {"id": "1", "name": "Alan", "location": "US"}, 
    {"id": "2", "name": "Bella", "location": "UK"}
]

I have following service:

    let users = getData();

    function getUsers() {
        return users;
    }
    function getData() {
        return $http
            .get("./data/users.json")
            .then(function(response) {
                return response.data;
            });
    }
    function addUser(user) {
        let id = users.$$state.value[users.$$state.value.length - 1].id++;
        users.$$state.value.push({
              // adding user
        })
    }

I am obtaining some very inconvenient object from $http.get. How to get it back to array representation?

share|improve this question
1  
Possible duplicate of How do I return the response from an asynchronous call? – Daedalus 16 hours ago
    
have you tried: return jQuery.parseJSON(response.data); ? – Cecilia 16 hours ago
    
I am not using jQuery, I use angular – Rudziankoŭ 16 hours ago
    
try : JSON.parse(response.data) – muhammad waqas 16 hours ago
2  
@Cecilia actually $http default response transform already do that. The problem here is about how promises works. – Lenilson de Castro 16 hours ago
up vote 3 down vote accepted

The problem here is the lack of compreension on how promises work, your $http call is not returning the response, but a promise of that request which is async. Promises are used exactly for this scenario, when you have async tasks and need to subscribe callbacks to its resolution.

Anyways, instead of trying to use the promise returned directly, you must subscribe a callback to the success topic, which in promises is given by the then(fn) method and feed your variable with the data returned from your chained promise on the $http.get().then ...$.

For example:

let users = [];

getData()
    .then(function (data) {
        users = data;
    });

function getUsers() {
    return users;
}

function getData() {
    return $http
        .get("./data/users.json")
        .then(function(response) {
            return response.data;
        });
}

function addUser(user) {
    let id = users.$$state.value[users.$$state.value.length - 1].id++;
    users.$$state.value.push({
          // adding user
    })
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.