J Castillo
J Castillo

Reputation: 3357

Doing a simple POST using $resource $save in angularjs

I am trying to get used to $resource and all its glory and I can't manage to do a simple post right.

To me using $http is simple.

I could do a POST like this:

$http.post("authorize/claim", collection).success(function() {

sending collection as a raw object or array as a PAYLOAD.

or like this:

$http.post("authorize/claim?claimItem="+collection).success(function() {

where am sending collection as a Query String.

Now when I try to do a simple post using $resource, data is always sent as a Query String. How can I send it as Array or Object?

here is what I was doing.

 var authoClaims = $resource('authorize/claim');

 authoClaims.save(collection);

Upvotes: 0

Views: 9876

Answers (1)

lukpaw
lukpaw

Reputation: 1613

Try this:

index.html

<!DOCTYPE html>
<html ng-app="myApp">

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular-resource.min.js"></script>
  <script type="text/javascript" src="script.js"></script>
</head>

<body>
  <div ng-controller="AuthorizeController">
    <form name="authorizeForm" novalidate>
      <label>Login</label>
      <input type="text" name="login" ng-model="authorizeClaim.login">
      <br/>
      <label>Code</label>
      <input type="text" name="code" ng-model="authorizeClaim.code">
      <br/>
      <button ng-click="doAuthorizeClaim()">Authorize claim</button>
    </form>
  </div>
</body>

</html>

script.js

var myApp = angular.module('myApp', ['ngResource', 'myAppServices']);

myApp.controller('AuthorizeController', ['$scope', 'Authorize',
  function($scope, Authorize) {

    $scope.doAuthorizeClaim = function() {
      Authorize.save($scope.authorizeClaim, function() {
        alert('Authorize claim saved');
      });
    };
  }
]);

var myAppServices = angular.module('myAppServices', ['ngResource']);

myAppServices.factory('Authorize', ['$resource',
  function($resource) {
    return $resource('/api/authClaims', {}, {});
  }
]);

Plunker example

If you run this example you can see on Network (Developer Tools/Firebug) something like this:

Request URL: http://run.plnkr.co/api/authClaims
Request Method: POST
Status Code: 404 Not Found
Request Payloadview source
{login:test1, code:code1}

So method POST works.

Upvotes: 4

Related Questions