Skip to content

Instantly share code, notes, and snippets.

@ramingar
Last active August 29, 2015 14:27
Show Gist options
  • Select an option

  • Save ramingar/45b0ee062bf7a729d05f to your computer and use it in GitHub Desktop.

Select an option

Save ramingar/45b0ee062bf7a729d05f to your computer and use it in GitHub Desktop.
Servicio de peticiones REST y control de la response de AngularJS 1.3+ #rest #restful #angularjs #angular #response
  /* Service */
  .factory('ServiceContainer', ['$resource', function($resource) {
    var defaultParams = {
      'page': 0,
      'size': 8
    };

    return {
      getResource: function (customParams) {
        return $resource(
          dataConfig.host + '/:resource_name/:id/:resource_detail_name',
          $.extend(customParams, defaultParams),
          {
            save: { method: 'POST' },
            update: { method: 'PUT' }
          },
          {
            'stripTrailingSlashes': 'true'
          }
        );
      }
    };
  }]);
    /* Code in your controller */
    $scope.delete = function (options) {
      $scope.feedback.state = '';
      $scope.feedback.message = '';

      $scope.parameters.id = $scope.model.id;

      ServiceContainer.getResource($scope.parameters).remove(
          $scope.model,
          function (data, header) {
            if (typeof data.cause == "undefined") {
              if (data.status > 400) {
                $scope.failure(data, null, options);          // HTTP STATUS CODE > 400... It counts as a success
              } else {
                $scope.success(data, header, null, options);  // Success!!
              }
            } else {
              $scope.failure(data, null, options);            // HTTP STATUS CODE = 400... It counts as a success and it doesn't return status code (but it returns a cause of error)
            }
          },
          function (response) {
            $scope.failure(response, null, options);          // HTTP STATUS CODE >= 500
          }
      );

    };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment