2013-10-17 2 views
4

URL에서 json을 가져올 때 데이터가 유효 할 때만 작업하고 싶습니다.AngularJS http.get valid json

내 접근 방식 지금까지 JSON를 사용하여 : 그러나

$http.get(
      'data/mydata.json' 
       + "?rand=" + Math.random() * 10000, 
      {cache: false} 
     ) 
      .then(function (result) { 

       try { 
        var jsonObject = JSON.parse(JSON.stringify(result.data)); // verify that json is valid 
        console.log(jsonObject) 

       } 
       catch (e) { 
        console.log(e) // gets called when parse didn't work 
       } 


      }) 

내가 구문 분석을 수행 할 수 있습니다 전에, 각 이미 나는이 오류를 던지는 방법 또는 다른에서 각도 방지 할 수있는 방법

SyntaxError: Unexpected token { at Object.parse (native) at fromJson (http://code.angularjs.org/1.2.0-rc.2/angular.js:908:14) at $HttpProvider.defaults.defaults.transformResponse (http://code.angularjs.org/1.2.0-rc.2/angular.js:5735:18) at http://code.angularjs.org/1.2.0-rc.2/angular.js:5710:12 at Array.forEach (native) at forEach (http://code.angularjs.org/1.2.0-rc.2/angular.js:224:11) at transformData (http://code.angularjs.org/1.2.0-rc.2/angular.js:5709:3) at transformResponse (http://code.angularjs.org/1.2.0-rc.2/angular.js:6328:17) at wrappedCallback (http://code.angularjs.org/1.2.0-rc.2/angular.js:9106:81) at http://code.angularjs.org/1.2.0-rc.2/angular.js:9192:26 angular.js:7861

자체를 실패 JSON을 확인해야합니까?

UPDATE : 솔루션 :

$http.get(
// url: 
'data/mydata.json' 
    + "?rand=" + Math.random() * 10000 

, 

// config: 
{ 
    cache: false, 
    transformResponse: function (data, headersGetter) { 
     try { 
      var jsonObject = JSON.parse(data); // verify that json is valid 
      return jsonObject; 
     } 
     catch (e) { 
      console.log("did not receive a valid Json: " + e) 
     } 
     return {}; 
    } 
} 
) 
+0

그것의 좋은 이야기하지만 당신은'result.data'을 게시하시기 바랍니다 수 있습니까? 또는 더 나은 Plunker –

+0

나는 동일한 문제점이있다. 반환되는 값 중 하나에서 시작되었습니다. 문제는 왜 json이 유효하지 않게 된 것입니까? 서버가 제대로 인코딩하지 않아야합니까? –

답변

4

당신은 $의 HTTP에 transformResponse을 대체 할 수 있습니다. 이 other answer을 확인하십시오.

0
내가 같은 일을 찾고 있었다

transformResponse 나는 일부는 $ http.get()되기 때문에 그것을 무시 심지어 내가 사용 transformResponse 매번 $ http.get를 (사용처럼 해달라고) 또는 해당 작업을 수행하되 json과 일부는 아닙니다.

그래서, 여기 내 솔루션입니다 :

myApp.factory('httpHandler', function($http, $q) {    
    function createValidJsonRequest(httpRequest) { 
    return { 
     errorMessage: function (errorMessage) { 
     var deferred = $q.defer(); 

     httpRequest 
      .success(function (response) { 
      if (response != undefined && typeof response == "object"){ 
       deferred.resolve(response); 
      } else { 
       alert(errorMessage + ": Result is not JSON type"); 
      } 
      }) 
      .error(function(data) { 
      deferred.reject(data); 
      alert(errorMessage + ": Server Error"); 
      }); 

     return deferred.promise; 
     } 
    }; 
    } 

    return { 
    getJSON: function() { 
     return createValidJsonRequest($http.get.apply(null, arguments)); 
    }, 
    postJSON: function() { 
     return createValidJsonRequest($http.post.apply(null, arguments)); 
    } 
    } 
}); 


myApp.controller('MainCtrl', function($scope, httpHandler) { 
    // Option 1 
    httpHandler.getJSON(URL_USERS) 
    .errorMessage("MainCtrl -> Users") 
    .then(function(response) { 
     $scope.users = response.users; 
    }); 


    // Option 2 with catch 
    httpHandler.getJSON(URL_NEWS) 
    .errorMessage("MainCtrl -> News") 
    .then(function(response) { 
     $scope.news = response.news; 
    }) 
    .catch(function(result){ 
     // do something in case of error 
    }); 


    // Option 3 with POST and data 
    httpHandler.postJSON(URL_SAVE_NEWS, { ... }) 
    .errorMessage("MainCtrl -> addNews") 
    .then(function(response) { 
     $scope.news.push(response.new); 
    }); 

}); 
관련 문제