Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to build angular $resource POST request to server?

I can't catch request on ASP.NET MVC project on server side controller from AngularJS:

    var appDirective = angular.module('app.directive', []);
    var xmplService = angular.module('app.service', ['ngResource']);
    var appFilter = angular.module('app.filter', []);        
    var app = angular.module('app', ['app.service', 'app.directive', 'app.filter', 'solo.table']);
    xmplService
    .factory('testResource1', function ($resource) {
         return $resource('/SoloAngularTable/TestMethod3', { id: '@id' }, { charge: { method: 'POST' } });
    });
    app
    .controller('ContentPlaceHolder1Controller', function ($scope, $http, testResource1) {                            
         testResource1.find({ id: 123 }, function (data) {                            
              alert('success');
         });
    });

On MVC Controller I have a method that can't catch request:

[HttpPost]
public JsonResult TestMethod3(int id)
{
    var data = new { User = "Alex" };
    return Json(data);
}

How to build simple request to server side with AngularJS $resource and catch request?

like image 312
Darien Fawkes Avatar asked Dec 26 '22 14:12

Darien Fawkes


1 Answers

find is not a default action for $resource. The defaults are:

{ 'get':    {method:'GET'},
  'save':   {method:'POST'},
  'query':  {method:'GET', isArray:true},
  'remove': {method:'DELETE'},
  'delete': {method:'DELETE'} };

You will have to create/specify the find action. You are currently creating/specifying a charge action. Perhaps this is what you meant to use?

If you want to use find, here is the fix:

.factory('testResource1', function ($resource) {
     return $resource('/SoloAngularTable/TestMethod3', { id: '@id' }, {
         charge: { method: 'POST' },
         find: { method: 'POST' } // Added `find` action
     });
});

If you meant to use charge, here is the fix:

.controller('ContentPlaceHolder1Controller', function ($scope, $http, testResource1) {                            
     testResource1.charge({ id: 123 }, function (data) {                            
          alert('success');
     });
});
like image 179
TheSharpieOne Avatar answered Dec 28 '22 06:12

TheSharpieOne