2013-10-17 43 views
4

當越來越從URL我只是想用它工作的一個JSON,當數據是有效的。AngularJS http.get驗證有效的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做這項工作,但是,我不喜歡使用transformResponse每次我使用$ http.get(),甚至重寫,因爲一些$ 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); 
    }); 

});