2014-09-15 2 views
0

각도 서비스를 작성하려고하는데 누락 된 것이있는 것 같습니다. 내 문제는이 HTTP 데이터 AngularJS : 값을 반환하지 않는 서비스

하지만 (크롬 개발 도구를 통해) 네트워크를 검사 할 때 제대로 외부 API를 호출하고 반환됩니다를 반환하지 않습니다

getPrepTimes() 방법 내 각도 컨트롤러에 어떤 값을 반환하지 않습니다 응답 나는 그것이 작동하는 문자열을 반환과 방법 getPrepTimes()을 확인

#my service 
'use strict'; 
angular.module('recipeapp') 
    .service('prepTimeService',['$http', function($http){ 
     this.prepTime = getPrepTimes(); 

     function getPrepTimes(){ 
      $http({ 
      url: '/prep_times/index.json', 
      method: 'GET' 
      }) 
      .success(function (data, status, header, config){ 
      return data; 
      }); 
     }; 
    } 
    ]); 




#controller 
'use strict'; 

angular.module('recipeapp') 
    .controller('recipeCtrl', ['$scope', 'prepTimeService', function($scope, prepTimeService){ 
    $scope.prep_time = prepTimeService.prepTime; 
    }]); 

같은 JSON 객체입니다. 여기서 무엇이 빠져 나갈 수 있겠습니까? $http 서비스에

+0

그것은 ... 당신이 할 수없는'반환되지해야한다 또한 다시 데이터를 얻기 위해 콜백을 사용하고 그것을 사용할 필요가 'AJAX 호출에서 콜백을 사용해야합니다. – tymeJV

답변

11

위의 경우 몇 가지 문제가 있습니다. this.prepTimegetPrepTimes()을 지정합니다. ()은 실제로는 getPrepTimes을 호출하며 실제로 호출하지는 않습니다! 과 같이 사용 지금

angular.module('recipeapp').service('prepTimeService',['$http', function($http){ 
    this.prepTime = getPrepTimes; 

    function getPrepTimes(callback) { 
     $http({ 
      url: '/prep_times/index.json', 
      method: 'GET' 
     }).success(function (data, status, header, config){ 
      callback(data); 
     }); 
    }; 
}]); 

을 그리고 :

prepTimeService.prepTime(function(data) { 
    $scope.prep_time = data; 
});  
+0

와우는 매우 빠르고 정확하며 감사합니다. .. :) – sameera207

1

통화는 약속 (그리고 값) 반환해야 즉, 비동기 있습니다 : 약속

angular.module('recipeapp') 
    .controller('recipeCtrl', ['$scope', 'prepTimeService', function($scope, prepTimeService){ 
    $scope.prep_time = prepTimeService.prepTime() 
     .success(function (data, status, header, config){ 
     $scope.someVar = data; 
     }); 
}]); 
1

랩 답변 :

this.prepTime = function() { 
    return $http({ 
     url: '/prep_times/index.json', 
     method: 'GET' 
    });   
}; 

을 그리고 컨트롤러 : 컨트롤러에서

var self = this; 

var deferred = $q.defer(); 

self.getPrepTimes = function() { 
     $http({ 
      url: '/prep_times/index.json', 
      method: 'GET' 
     }) 
       .success(function(data, status, headers, config) { 

        if (data.error === undefined) { 
         deferred.resolve(data); 
        } else { 
         if (data.error !== undefined) { 

         } else { 
          deferred.reject(data); 
         } 
        } 

       }).error(function(data, status, headers, config) { 
      deferred.reject(data); 
     }); 
     return deferred.promise; 
    }; 

은 전화 :

prepTimeService.getPrepTimes().then(function(result) { 
    $scope.prep_time = result; 
    }, 
    function(error) { 
    // show alert   
    }); 
+0

대답 해줘서 고마워, 나는 꽤 새롭다. 그리고 나를 위해'약속한다. '는 여전히 혼란 스럽다. .. 잠시 그들을 멀리하려고 노력하고있다. :) – sameera207

+0

@ sameera207 미래 숙제 :) 약속은 당신에게 능력을 준다. 컨트롤러에 오류도 전달합니다. http가 실패하고 팝업을 표시하고 싶다고 생각하면이 경우 대답을 거절하고 컨트롤러에서 'function (error)'을 입력하십시오. –

관련 문제