0

I am trying to use httml get to get the json

I have something like

.controller('testController', function($scope, $state, $http) {
  $http({
        url: "/json/test.json",
        method: "GET",
    }).success(function(data) {
        $scope.testData = data;
        console.log(data)
    });

  //outside of the $http scope but under the same controller, I have
  //It shows undefined. 
   console.log($scope.testData)
})

I know we have to keep data our of the login codes so I don't want to modify the data inside the $http. Is there anyway to accomplish this? Thanks!

2
  • It's an async call, thus undefined of the success handler. So the answer is no. Commented Apr 28, 2014 at 18:17
  • Whats your console logging in the success function? The success function is just a function that can exist anywhere. Commented Apr 28, 2014 at 18:19

2 Answers 2

1

First, don't put this in a controller. Move it to a Service. That's what Services are designed for.

Second, the $http service is asynchronous. Your result only exists in the success callback, and your console.log will be called before the http request is finished. You need to assign it to a scope variable to use it outside of the callback, and expect it to be empty until the call back is complete.

http://blog.brunoscopelliti.com/deal-with-users-authentication-in-an-angularjs-web-app provides an example of an AngularJS authentication service, if that's what you're doing.

To go with your example:

.controller('testController', function($scope, $state, $http) {
  $scope.testData = {};
  $http({
        url: "/json/test.json",
        method: "GET",
    }).success(function(data) {
        $scope.testData = data;
        $scope.logData();
    });
  $scope.logData = function() {
    console.log($scope.testData);
  }
});
Sign up to request clarification or add additional context in comments.

Comments

1

This plnkr code is created in order to give your answer, yes you can have the $scope.testData outside the http request.

Have a look!!

var app = angular.module('plunker', []);

app.controller('testController', function($scope, $http) {
  $http({
        url: "test.json",
        method: "GET",
    }).success(function(data) {
        $scope.testData = data;
        alert(data);
        callA();
    });

  function callA(){
   alert($scope.testData);
  }
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.