I have an angular post method through which I want to pass data to web api post but doesn't seem to work. What could I be doing wrong?
customerPersistenceService.js
var customerPersistenceService = function ($http, $q) { return { save: function(customer) { var deferred = $q.defer(); $http.post("/api/customers", customer) .success(deferred.resolve) .error(deferred.reject); return deferred.promise; }, update: function(customer) { var deferred = $q.defer(); $http.put("/api/customers/{id}" + customer.id, customer) .success(deferred.resolve) .error(deferred.reject); return deferred.promise; } }; }; customerEditCtrl.js
function customerEditCtr($stateParams, $location, customerPersistenceService) { var vm = this; vm.editableCustomer = {}; vm.selectedCustomerId = $stateParams.id; customerPersistenceService.getById(vm.selectedCustomerId).then( function (customer) { vm.editableCustomer = customer; }); }; vm.saveCommand = function () { if (saveCustomer) { var customer = vm.editableCustomer; customer.id = vm.selectedCustomerId; if (customer.id !== 0) { customerPersistenceService.update(customer).then( function (result) { return result.data; }); } else { customerPersistenceService.save(customer).then( function (result) { return result.data; }); } } }; }; In the CustomerAPIController.cs my methods look like these:
[HttpPost] public HttpResponseMessage Post([FromBody]Customer newCustomer) { try { if (ModelState.IsValid) { _customerService.AddNewCustomer(newCustomer); return Request.CreateResponse(HttpStatusCode.Created, newCustomer); } else { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } } catch (Exception ex) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex); } } [HttpPut] public HttpResponseMessage Put(int id, [FromBody]Customer editableCustomer) { if (!ModelState.IsValid) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } if (id != editableCustomer.Id) { return Request.CreateResponse(HttpStatusCode.BadRequest); } try { _customerService.UpdateCustomer(editableCustomer); return Request.CreateResponse(HttpStatusCode.OK, "{success:'true', verb:'PUT'}"); } catch (DbUpdateConcurrencyException ex) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex); } } Update: After some investigation, I realise the vm.editableCustomer seems to contain an array of all customer objects making it hard to pass to the Web API POST. I fail to understand how this object gets assigned with all customer objects.
$http.put/post/delete/getreturns you a promise, so you don't have to include the$qlibrary, and that the$qis in the$http