0
使用承諾時遇到問題。 我的控制器是javascript中的句柄承諾
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)
});
}
這是我的服務
angular.module('shoppingPad').service('customerService', customerService);
function customerService($q, $http,restService) {
//this is deferred object which will resolve or resolve the promise
var deferred = $q.defer();
//a function to add customer data to backend used service.it takes customer object as 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;
});
};
這是我restService.js
angular.module('shoppingPad').service('restService',restService);
function restService($http){
//set port number and 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
我收到錯誤在我的控制器 錯誤:customerService.addCustomer( ...)未定義。 如果IAM做錯了請用我的好代碼糾正我
我不認爲他知道如何處理承諾。如果他知道他不會問這個。也許你還需要添加一個例子。 –
@TJ完成。控制器中添加處理程序 –