angularjs - handle promises in javascript -
i having trouble when using promise. controller is
angular.module('shoppingpad').controller('customerctrl', customerctrl); function customerctrl($scope, customerservice){ $scope.addcustomer=function() { alert("inside add customer function"); var customer={ name: $scope.name, number: $scope.number }; customerservice.addcustomer(customer).then(function(response){ console.log(response); }, function(error){ console.log(error) }); }
this service
angular.module('shoppingpad').service('customerservice', customerservice); function customerservice($q, $http,restservice) { //this deferred object resolve or resolve promise var deferred = $q.defer(); //a function add customer data backend used service.it takes customer object paramater. this.addcustomer = function(customer) { return restservice.postrequest('customers/info',customer,function(response){ deferred.resolve(response.data); return deferred.promise; }, function(error){ deferred.reject(error); return deferred.promise; }); };
this restservice.js
angular.module('shoppingpad').service('restservice',restservice); function restservice($http){ //set port number , baseurl here var port=3001; var baseurl="http://localhost:"+port; //generic getrequest function this.postrequest=function(url,data,successcallback,failurecallback){ $http({ method:'post', url:baseurl+"/"+url, data:data }).then(function(response){ successcallback(response); }, function(error){ alert("internal server error"); failurecallback(error); }); };//end of postrequest function }//end of service
i getting error in controller error: customerservice.addcustomer(...) undefined. if iam doing wrong please correct me code
the problem in code not returning $http()
call in this.postrequest()
method.
change method below:
this.postrequest=function(url,data){ return $http({ method: 'post', url: baseurl+"/"+url, data: data }); };
don't pass success , error callbacks in return promise upstream method , handle promise. also, since every return of promise promise in don't need create new promise using $q
in customerservice
. return same promise postrequest
method below:
this.addcustomer = function(customer) { return restservice.postrequest('customers/info', customer); }
this way don't need additional unnecessary promises.
now in controller can handle returned promise below:
$scope.addcustomer=function() { alert("inside add customer function"); var customer={ name: $scope.name, number: $scope.number }; customerservice.addcustomer(customer) .then(function(response){ console.log(response); }) .catch(function(error){ console.log(error) }); }
also have used .catch
instead of passing error callback second parameter .then
because has added advantage of catching errors in success callback along errors returned promise
Comments
Post a Comment