简体   繁体   English

AngularJS http.get验证有效的json

[英]AngularJS http.get verify valid json

When getting a json from a URL I only want to work with it, when the data is valid. 从URL获取json时,我只想使用它,当数据有效时。

my approach so far by using 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
                }


            })

However before I can do the parsing, angular already fails itself 然而,在我可以进行解析之前,angular已经失败了

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 SyntaxError:$ HttpProvider.defaults.defaults.transformResponse上fromJson( http://code.angularjs.org/1.2.0-rc.2/angular.js:908:14 )的意外标记{at Object.parse(native) ( http://code.angularjs.org/1.2.0-rc.2/angular.js:5735:18 )在http://code.angularjs.org/1.2.0-rc.2/angular.js: 5710:12位于forData的Array.forEach(native)( http://code.angularjs.org/1.2.0-rc.2/angular.js:224:11 ),位于transformData( http://code.angularjs。在wrappedCallback的transformResponse( http://code.angularjs.org/1.2.0-rc.2/angular.js:6328:17 )上的org / 1.2.0-rc.2 / angular.js:5709:3http://code.angularjs.org/1.2.0-rc.2/angular.js:9106:81 )在http://code.angularjs.org/1.2.0-rc.2/angular.js:9192 :26 angular.js:7861

How can I prevent angular from throwing this error or how else should I handle verifying the JSON ? 如何防止角度抛出此错误或我应该如何处理验证JSON?

UPDATE: Solution: 更新:解决方案:

$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 {};
    }
}
)

You can override transformResponse in $http. 您可以在$ http中覆盖transformResponse Check this other answer . 检查这个其他答案

I was looking for the same thing, and transformResponse does the job, BUT, I dont like using transformResponse everytime i use $http.get() or even overriding it because some $http.get() will be json and some not. 我正在寻找相同的东西,并且transformResponse完成了这项工作,但是,我不喜欢每次使用$ http.get()或甚至覆盖它时都使用transformResponse,因为一些$ http.get()将是json而一些不是。

So, here is my solution: 所以,这是我的解决方案:

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

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM