LargeCrimsonFish LargeCrimsonFish - 1 year ago 119
AngularJS Question

Saving an $http response object as a $scope variable

I asked a related question earlier today on stackoverflow but due to both the complexity of the code (not being able to post it) and my own noviceness I wasn't able to really implement a solution from the answers given.

So my question now is, for a code such as:

$http.get(ArbitraryInput).then(function (response) {$ = response});

(you can substitute "then" with "success" above, I use "then" because success is deprecated according to the updated $http api)

How do I actually save the response object in $ From what I've been doing so far, $ is "undefined" when I later typed in the code:




Apparently if I put console.log($; inside the console will display what I want for $ But if it is outside, it will remain "undefined" in the console. In other words:

$http.get(ArbitraryInput).then(function (response) {$ = response; console.log($;});

will return whatever sort of object response was. in the console, but

$http.get(ArbitraryInput).then(function (response) {$ = response;});

will return "undefined" in the console.

Answer Source

You need to leverage the fact that $http.get returns a promise, and chain to that promise in any code that needs to access the resolved data:

app.controller('Ctrl', function($scope, mainInfo){
    var request = $http.get(ArbitraryInput).then(function (response) {
        $ = response; 
        return response; // this will be `data` in the next chained .then() functions

    request.then(function (data) {/* access data or $ in here */});

    $scope.someFunction = function () {
        request.then(function (data) {/* access data or $ in here */);
}) ;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download