在工作完成后,角度服务不会在控制器中返回成功

时间:2017-01-16 11:56:10

标签: javascript angularjs angularjs-scope

我在服务中调用一个方法,当服务工作完成后,它应该返回带有数据的控制器, 并继续工作,但在调用服务并生成数据后,该方法是控制器停止并在控制台中返回错误:

错误:

Error: d is undefined
sendOtp/<@http://xxxxxxx:8087/controller/resources/static/js/controller/mainController.js:71:14
processQueue@https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:14634:28
scheduleProcessQueue/<@https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:14650:27
$RootScopeProvider/this.$get</Scope.prototype.$eval@https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:15916:16
$RootScopeProvider/this.$get</Scope.prototype.$digest@https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:15727:15
$RootScopeProvider/this.$get</Scope.prototype.$apply@https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:16024:13
done@https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:10511:36
completeRequest@https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:10683:7
requestLoaded@https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:10624:1

控制器:

app.controller('signController', ['$scope','signUpService','$location','$rootScope', function($scope, signUpService, $location, $rootScope) {
$scope.OTP='';

function sendOtp(pNumber, countryId){    

    if(pNumber!==null){
    $rootScope.pNumber = pNumber;
    signUpService.sendPhoneOtp(pNumber,countryId)       
     .then(  
        function(d) {
            /*$location.path('/otp', false);*/
            $scope.OTP = d.response.result.otp;
            console.error('OTP SENT SUCCESSFULLY'+$scope.OTP);
            alert($scope.OTP);

        },
        function(errResponse){
            console.error('Error while fetching OPT of NUMBER');
        }           
    );
    }else{
        alert("Number can not be empty");
    }

} 

方法内部服务:

    function sendPhoneOtp(pNumber,countryId){
    var deferred = $q.defer();
     $http({
            method: 'POST',
            url: 'https://xxxxx.com/service/verify/phone',
            data: {
                    phone: pNumber,
                    countryId: countryId
                    }
         }).success(function(response){
             deferred.resolve(response.data);

        }).error(function(errResponse){
             console.error('Error while OTP');
             deferred.reject(errResponse);
        });
return deferred.promise;
}

1 个答案:

答案 0 :(得分:1)

尝试将您的sendPhoneOtp功能更改为:

function sendPhoneOtp(pNumber, countryId) {
  return $http({
           method: 'POST',
           url: 'https://xxxxx.com/service/verify/phone',
           data: {
             phone: pNumber,
             countryId: countryId
           }
         }).then(function(response){
           return response.data;
         }).catch(function(errResponse) {
           console.error('Error while OTP');
         });
  }

在已弃用的success函数中没有data属性,您也不需要使用$q服务,因为$http本身就是一个承诺