2014-04-28 2 views
0

는 내가 JSON을 얻을 수 httml GET을 사용하려고필자의 경우 json 데이터를 얻는 방법은 무엇입니까?

나는 우리가 데이터를 유지하는 것을 알고

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

같은 일이 우리의 로그인 코드 그래서 데이터를 수정하지 않으려는이 $ http 내부. 이 작업을 수행 할 여지가 있습니까? 감사!

+0

비동기 호출이므로 성공 처리기가 정의되지 않았습니다. 그래서 대답은 '아니오'입니다. – Johan

+0

당신의 콘솔이 성공 함수에 로그인하는 이유는 무엇입니까? 성공 함수는 어디서든 존재할 수있는 함수입니다. –

답변

1

먼저 컨트롤러에 넣지 마십시오. 그것을 서비스로 옮기십시오. 그것이 바로 서비스가 설계된 것입니다.

두 번째로, $ http 서비스는 비동기식입니다. 결과는 성공 콜백에만 존재하며 http 요청이 완료되기 전에 console.log가 호출됩니다. 범위 변수에 할당하여 콜백 외부에서 사용하려면 콜백이 완료 될 때까지 비어 있어야합니다.

http://blog.brunoscopelliti.com/deal-with-users-authentication-in-an-angularjs-web-app은 AngularJS 인증 서비스의 예를 보여줍니다.

은 예제를 이동하려면 :

.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); 
    } 
}); 
1

plnkr code이 답을주기 위해 만든이, 그래 당신은 HTTP 요청 외부 $ scope.testData을 가질 수 있습니다.

보세요!

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); 
    } 
}); 
관련 문제