0

I have an Angular service that uses $http to get a json file.

App.factory('jsonFile', function($http) {
    var promise;
    var jsondata = {
        get: function() {
            if ( !promise ) {
                var promise =  $http.get('src/app_preprocess/data_json.js').success(function(response) {
                    return response.data;
                });
                return promise;
            }
        }
    };
    return jsondata;
});

And a controller

App.controller('firstCtrl', function (jsonFile , $scope) {
    jsonFile.get().then(function(d) {
        $scope.header = d.data.PACKAGE.ITEM[0] 
    })
});

This works well.

My question is why can I not add the outcome of the http to a variable instead of the scope like so...?

App.controller('firstCtrl', function (jsonFile , $scope) {
    var output;
    output = jsonFile.get().then(function(d) {
        return d.data.PACKAGE.ITEM
    });
    $scope.header = output[0];
});
0

1 Answer 1

1

Because jsonFile returns a promise and you try to use output before it returns.. only inside the then clause you can be assured the promise would return in the expected timing. outside of it - you can't now due to the async nature of http calls.

You can read more about promises in angular here

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that makes perfect sense

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.