2017-01-16 11 views
0

Я вызываю метод внутри Сервиса, и когда работа службы завершена, он должен вернуться к контроллеру с данными, и продолжить работу дальше, но после того, как услуга называется и генерируется данных метод остановки контроллера и возврата ошибки в консоли:Угловое обслуживание не возвращает успех в контроллере после того, как работа выполнена в сервисе

ошибка:

Error: d is undefined 
sendOtp/<@http://xxxxxxx:8087/controller/resources/static/js/controller/mainController.js:71:14 
[email protected]://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</[email protected]://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:15916:16 
$RootScopeProvider/this.$get</[email protected]://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:15727:15 
$RootScopeProvider/this.$get</[email protected]://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:16024:13 
[email protected]://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:10511:36 
[email protected]://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js:10683:7 
[email protected]://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

Читайте о [обещании анти-шаблона] (http://taoofcode.net/promise-anti-patterns/) вы можете просто «вернуть $ http (...);' ins tead –

+0

Используйте 'console.log()' для регистрации 'response', согласно сообщению об ошибке' d' is 'undefined' – Satpal

+0

Проверьте, какая структура объекта ответа у вас есть. Присутствует ли 'response.data'? – Sangharsh

ответ

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 это само по себе

+0

Это было действительно полезно, я не знал, что успех был устаревшим. Я точно скопировал ваш код и он работал отлично по мере необходимости, спасибо – Sidharth

 Смежные вопросы

  • Нет связанных вопросов^_^