$ http.post in angularJS goes in error without debug mode only.in in debug mode it works fine.why?

here is my javascript code

$scope.addUser = function () { debugger; url = baseURL + "AddUser"; $scope.objUser = []; $scope.objUser.push( { "ID": '0', "UserName": $scope.txtUserName, "Password": $scope.txtPassword, "Role":"Non-Admin" }); $http.post(url,$scope.objUser[0]) .success(function (data) { debugger; alert("S"); window.location = "../View/Login.html"; }).error(function () { debugger; alert("e"); }); } 

here is my server method code

 [HttpPost] public int AddUser(UserModel user) { //_entity.Configuration.ProxyCreationEnabled = false; tblUser objUser = new tblUser(); objUser.UserName = user.UserName; objUser.Password = user.Password; objUser.Role = user.Role; _entity.tblUsers.Add(objUser); _entity.SaveChanges(); return objUser.ID; } 
+6
source share
1 answer

You can use promises to get an answer. it can be inside the service and call it whenever you want to use it.

 this.addUser = function (obj) { var datosRecu = null; var deferred = $q.defer(); var uri = baseUrl + 'addUser'; $http({ url: uri, method: 'post', data: angular.toJson(obj) }).then(function successCallback(response) { datosRecu = response; deferred.resolve(datosRecu); }, function errorCallback(response) { datosRecu = response; deferred.resolve(datosRecu); }); return deferred.promise; }; 

Also .error and .success are deprecated.

PD: parameter data: inside $http matches the body. if you want to send parameters, you should use params:{}

EDIT: Here I will leave you a link how promises works. Angular promises This mainly helps to process data asynchronously

the above example can be used inside a service like this

 myApp.service('myService', function($q, $http){ // here your services.... }); 

a service can be entered inside any controller to provide the data you want inside your functions.

 myApp.controller('myController', function($scope, myService){ $scope.list = function(){ $promise = myService.getAll(); // this will be the name of your function inside your servive $promise.then(function(data){ console.log(data); //here you can se your promise with data like status and messages from the server. }); }; }); 

Hope this helps.

0
source

All Articles