ElenaDBA ElenaDBA - 1 month ago 11
AngularJS Question

How to retrieve identity value from AngularJS POST request

I have the following method in my Web API

public IHttpActionResult PostNewOrder(myClass.Order ord1)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
using (MyContext ctx = new MyContext())
{

ctx.Orders.Add(ord1);
ctx.SaveChanges();

return CreatedAtRoute("DefaultApi", new { id = ord1.OrderID }, ord1);

}
}


I call the API from AngularJS as follows:

function CreateOrder(url, inData) {
$http.post(url, inData)
.success(function (data, status, header) {
$scope.result = data;
console.log("Order ID is " + $scope.result.OrderID);
})
.error(function (data, status, header) {
$scope.result = "Data: " + data +
"<hr />status: " + status;
console.log(header.responseText);
});
}


The above logs the correct Order ID, but how can i retrieve that ID from outside the function? After function call?

CreateOrder('http://server/AppName/api/PostNewOrder', ord1);


using
return $scope.result.OrderID
inside the function does not work

I also tried calling the function as follows:

$scope.NewOrderID =CreateOrder('http://server/AppName/api/PostNewOrder', ord1);


while adding return to my function

function CreateOrder(url, inData) {
$http.post(url, inData)
.success(function (data, status, header) {
$scope.result = data;
console.log("Order ID is " + $scope.result.OrderID);
return $scope.result.OrderID;
})
.error(function (data, status, header) {
$scope.result = "Data: " + data +
"<hr />status: " + status;
console.log(header.responseText);
});
}


but
$scope.NewOrderID
comes up undefined

Answer

Use .then instead of .success and return a promise. Else if you still want to go with .success, use deferred API and return the promise anyway. Then in the calling code, use .then.

a service

        app.service('OrderService', function ($http, $q) {

            return {
              CreateOrder: CreateOrder
            };

            function CreateOrder(url, inData) {

            var deferred = $q.defer();

            $http.get(url, inData)
               .success(function (data, status, header) {

               deferred.resolve({
                 OrderID:  data.id
               });


               })
               .error(function (data, status, header) {
               deferred.reject(msg);
               });

               return deferred.promise;

            }
        });

in controller OrderService.CreateOrder('order.json', null).then(function(id){ console.log(id); });

Refer to this and this on how to make this decision. But the general verdict is not to use .success if inside a service, but to go for .then. Again it is up to you. It is just that .success is implemented by AngularJS that way.

My Working plnkr - http://plnkr.co/edit/uCx1PiliTDPT3hYh5YXI?p=preview: