Comment

Daniel Sánchez

Everytime i used $http.get() / $http.post() to retrieve some json data i had to make something like this to be sure everything was json valid and error free from server,

app.controller('MainCtrl', function($scope, httpq) {
    $http.get('https://www.mysite.com/users/')
        .success(function(response){
              if (response != undefined && typeof response == "object") {
                     $scope.users = response.users;
              } else {
                     alert("MainCtrl -> Users: Result is not JSON type");
              }
        })
        .error(function(data) {
            alert("MainCtrl -> Users: Server Error");
        });

    $http.get('https://www.mysite.com/news/')
       .success(function(response){
              if (response != undefined && typeof response == "object") {
                     $scope.news= response.news;
              } else {
                     alert("MainCtrl -> News: Result is not JSON type");
              }
        })
        .error(function(data) {
            alert("MainCtrl -> News: Server Error");
        });
});


That's because entering the .success() does not guarantee its a json object, you can return from server a simple print "hello world"; and it will still enter .success()

Therefore, I was looking for something more practical, i ended on this page and after some reading i endend with this:


var app = angular.module('myapp');

app.factory('httpq', 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));
    }
  }
});







app.controller('MainCtrl', function($scope, httpq) {
 
  httpq.getJSON('https://www.mysite.com/users/')
    .errorMessage("MainCtrl -> Users")
    .then(function(response) {
         $scope.users = response.users;
    });

  httpq.getJSON('https://www.mysite.com/news/')
    .errorMessage("MainCtrl -> News")
    .then(function(response) {
         $scope.news = response.news;
     })
     .catch(function(result){
          // do something in case of error
     });

  httpq.postJSON('https://www.mysite.com/news/', { ... })
    .errorMessage("MainCtrl -> addNews")
    .then(function(response) {
         $scope.news.push(response.new);
    });

});



Now i can use something like this knowing:
- It will be json valid.
- It will handle server errors.
- It will automatically display alerts showing a custom error message
- If it enters .then() everything went as planned.


Thanks Peter