Rudziankoŭ
Rudziankoŭ

Reputation: 11251

AngularJS: retrieve array from object after $http get

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?

Upvotes: 0

Views: 1209

Answers (1)

lenilsondc
lenilsondc

Reputation: 9800

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

Upvotes: 3

Related Questions