2014-09-05 4 views
1

방금 ​​Angular를 배우기 시작했고 이제는 JSON에서 가져온 일부 레코드를 보여주는 웹 응용 프로그램을 사용 중입니다. 내가이 길에 그 구문 분석하고AngularJS parse JSON

"results": [ 
    { 
    "easy": false, 
    "id": 1, 
    "title": "title", 
    } 
] 

이에 (그래서 지금 내가 ID를 얻을 필요가이 JSON 파일에서 오전

var app = angular.module("DB", []); 

app.controller("Controller", function($scope, $http) { 
    $http.defaults.headers.common["Accept"] = "application/json"; 
    $http.get('api_url'). 

    success(function(data, status, headers, config) { 
     $scope.thing = data.results; 
    }); 
}); 

을 (나에게 올바른 것) 같은 JSON 본다 경우 1) 그 ID와 함께 첫 번째 파일에서 결과에 대한 자세한 정보를 얻으려면 api.com/game/{id} 새로운 요청을해야합니다.

가장 좋은 방법은 무엇입니까?

+0

않습니다. – MohamedAbbas

답변

1
$http.get('api.com/game/' + $scope.thing.id, function(...){ }); 

주목할 점은 수동으로 각도가있는 JSON을 구문 분석 할 필요가 없다는 점입니다. 그것은 당신을 위해 그것을 할 것입니다. 따라서 data.results에는 이미 응답을 나타내는 개체가 있습니다.

var app = angular.module("DB", []); 

     app.controller("Controller", function($scope, $http) { 
      $http.defaults.headers.common["Accept"] = "application/json"; 
      $http.get('api_url'). 

      success(function(data, status, headers, config) { 
       $scope.thing = data.results; 
       $scope.id=data.results[0].id; 
       gameInfo(); 
      }); 
     }); 

    var gameInfo=function(){ 
    $http.get('api.com/game/'+$scope.id). 

      success(function(data, status, headers, config) { 
       $scope.newThing = data; 
      }); 
    } 
0

난 당신이 이렇게 할 경우는 좋은 아이디어라고 생각합니다. 그것은 다른 것들 사이에서 매개 변수 교체 (사용자 정의 인터셉터 등)

https://docs.angularjs.org/api/ngResource/service/ $ 자원 당신은 사용자 공장 또는 API 호출은 다음 컨트롤러에 공장이나 서비스를 주입 할 수있는 서비스를해야

0

또한 당신에게 HTTP 요청을보다 세밀하게 제어 할 수있는 모듈입니다 ngResource를 살펴 :