2014-04-26 4 views
0

AngularJS를 처음 사용하고 있으며 기존 Spring MVC 기반 웹 응용 프로그램을 마이그레이션하고 있습니다. 가장 좋은 점은 스프링 컨트롤러에서 반환 된 JSON을 조작하는 JS를 많이 제거한다는 것입니다.Spring REST API에서 AngularJS 읽기 JSON

Angular 컨트롤러에서 수동으로 JSON을 할당하면 올바르게 작동합니다. 내 문제는 $ HTTP를 사용하여 스프링 MVC 컨트롤러에서 데이터를 검색 할 때 유효한 응답 (200)을 얻었음에도 불구하고 제대로 작동하지 않는 것처럼 보이고 FF는 정교하게 구조화 된 JSON을 보여주고있다.

Console in Firefox

나는 심지어 서비스에 JSON을 인쇄하고 올바른입니다 볼 수 있습니다.

enter image description here

지금이보고 블라인드 갔어요 그리고 나는 내가이 만든 기본 변수 할당 실수 바라고 있어요.

내 app.js는

'use strict'; 

// Angular app level module which depends on controllers, and services 
angular.module('WebClient', [ 
    'WebClient.controllers', 
    'WebClient.services' 
]); 

아래는 각 컨트롤러와 주석 테스트 코드가 스프링 컨트롤러에서 반환 된 같은 JSON입니다. 테스트 코드의 주석을 풀면 모든 것이 예상대로 작동하고 Batarang이 저에게 멋지게 형식화 된 모델을 보여줍니다.

내 controllers.js은 : 서비스


'use strict'; 

// K,V pairs of facets to search hits 

angular.module('WebClient.controllers', []). 
    controller('facetsController', function($scope, facetsAPI) { 
     $scope.facetsList = []; 
     $scope.mychecker = true; 

     facetsAPI.getFacets().success(function (response) { 
      $scope.facetsList = response.facetsAPI; 
      console.log("Controller successfully got facets"); 
      console.log($scope.facetsList); 
      console.log(response.facetsAPI); 

//  $scope.facetsList = [ 
//   { 
//    "id": "type", 
//    "name": "type", 
//    "facet-fields": [ 
//     { 
//      "id": "contents", 
//      "count": 44008, 
//      "name": "contents" 
//     }, 
//     { 
//      "id": "lessons", 
//      "count": 0, 
//      "name": "lessons" 
//     }, 
//     { 
//      "id": "sentences", 
//      "count": 0, 
//      "name": "sentences" 
//     }, 
//     { 
//      "id": "all", 
//      "count": 44008, 
//      "name": "All" 
//     } 
//    ] 
//    } 
//   ] 


     }); 
    }); 

은 $ HTTP 요청은 잘 형성 JSON 출력 CONSOLE.LOG하는 봄과 디버그 라인에서 제대로 (데이터) 데이터를 검색한다. 이 서비스는 유효한 데이터를 보는 마지막 지점입니다. 이 시점 이후 로깅 진술과 Batarang은 유효한 데이터를 더 이상 볼 수 없습니다.

내 services.js은 다음과 같습니다


angular.module('WebClient.services', []). 
    factory('facetsAPI', function($http) { 

     var facetsAPI = {}; 

     facetsAPI.getFacets = function() { 
      return $http({url: 'http://localhost:8080/api/facets'}) 
       .success(function(data, status, headers, config) { 
        // this callback will be called asynchronously 
        // when the response is available 
        console.log("Success getting JSON"); 
        console.log("Status: " + status); 
        console.log(data); 
       }) 
       .error(function(data, status, headers, config) { 
       // called asynchronously if an error occurs 
       // or server returns response with an error status. 
       console.log("Error getting JSON"); 
       console.log("Status: " + status); 
      }); 
     } 

     return facetsAPI; 
    }); 

내 봄 컨트롤러가하는 모든 검색 조작 및 패싯 계산 및 JSON을 반환합니다. 이 JSON이 Jsonlint.com에서 유효하다는 것을 확인했습니다. (I는 각도와 더 잘 할 수있는이 검색 조작의 일부를 알고 있지만 우리는 점진적으로 리팩토링있어 나는 잠시 동안 이러한 측면에 초점을 맞춘거야)


    @RequestMapping(value = "/api/facets", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.GET) 
    public @ResponseBody String getFacets() {

// Store all facets in a list for later conversion to JSON array 
    List<Object> listOfFacets = new ArrayList<Object>(); 

    ... 
    ... 
    ... 

    // Add all the facets to a single map for conversion to JSON 
    Map<String, Object> outerMap = new HashMap<String, Object>(); 
    outerMap.put("facets", listOfFacets); 

    JSONArray facetsAsJson = new JSONArray(listOfFacets); 
    return facetsAsJson.toString(); 
} 

이 어떤 도움이 고맙습니다.

+0

그것을 수정해야합니다. 두 번째 .success가 아마도 등록되지 않았습니까? "Controller successfully facets"에서 인쇄물을 가져 옵니까? 또한 $ http 문자열 또는 구문 분석 JSON에서 반환 된 응답은 무엇입니까? 아마도 시도해보십시오 : $ scope.facetsList = JSON.parse (response) .facetsList; – eshortie

+0

감사합니다 # 모두 콘솔에서 디버그를 볼 수있는 두 가지 .success 함수가 등록되었습니다.컨트롤러에서 컨트롤러가 성공적으로 패싯을 얻었으며 JSON을 성공으로 가져 왔습니다. 따라서 두 가지 성공 함수 모두 등록 및 실행이었습니다. 아래의 Anthony의 답변에 따르면 근본 원인은 $ http의 응답 구조를 잘못 해석 한 것입니다. 일단 모든 조명이 초록색으로 바뀌면 예상대로 작동하기 시작했다. –

답변

2

은 이미 패싯 배열이어야하며 응답에는 facetsAPI 속성이 없으므로 실제로 undefined$scope.facetsList에 할당합니다. response.facetsAPIresponse에 변경 당신은 $에 http 약속에 성공 기능을 결합했지만 다음 컨트롤러에서 동일 할 서비스에 ...

facetsAPI.getFacets().success(function (response) { 
    $scope.facetsList = response; 
    // ... 
} 
+0

Anthony에게 감사드립니다. 정확하게 그랬습니다. 나는 튜토리얼을 따라 갔고 거기에 무엇이해야했는지 의문을 제기하지 않았다. 이제 당신이 지적 했으니 나를 위해 그것을 정리했습니다. –

관련 문제