控制器没有得到工厂的回复

时间:2015-11-04 11:32:26

标签: angularjs

我正在尝试通过在服务中执行http请求来清理我的控制器,但由于某种原因,我的控制器中的函数没有从服务获得响应。

我的控制器中有这个功能,

  $scope.addMovie = function() {

    addMovie.add().then(function(response){
      if(response){
        console.log ('Response')
      } else {
        console.log ('No reposone')
      }
    });

这是服务,

(function(){
  "use strict";

  angular.module('addMovieseat')

  .factory('addMovie',

    function($http, $q){
      return{
        add: function(){
          var deferred = $q.defer();

          'http://api.themoviedb.org/3/movie/206647?api_key=a8f7039633f2065942cd8a28d7cadad4&append_to_response=releases'
          // Search for release dates using the ID.
          var base = 'http://api.themoviedb.org/3/movie/';
          var movieID = $(event.currentTarget).parent().find('.movieID').text()
          var apiKey = 'a8f7039633f2065942cd8a28d7cadad4&query='
          var append_to_response = '&append_to_response=releases'
          var callback = 'JSON_CALLBACK'; // provided by angular.js
          var url = base + movieID + '?api_key=' + apiKey + append_to_response + '&callback=' + callback;

          $http.jsonp(url,{ cache: true}).
            success(function(data, status, headers, config) {

              if (status == 200) {

                deferred.resolve(data.results);
                console.log ('Succes getting data')

              } else {
                console.error('Error happened while getting the movie list.')
              }

            }).
            error(function (data, status, headers, config) {
              console.error('Error happened while getting the movie list.')
              deferred.resolve(false);
            });

            $(".search_results").fadeOut(250);

            return deferred.promise;
        }
      }
    })

})();

当我从控制器运行$scope.addMovie函数时,控制台日志会从服务中显示Succes getting data,然后从控制器中的函数显示No response。这里缺少什么?

//编辑。我现在正在尝试将服务中的数据插入到控制器的范围中,

$scope.addMovie = function() {

  $scope.movieListID = {};
  console.log ('empty' + $scope.movieListID)

  movieAdd.add()
    .then(function(response){
      $scope.movieListID = response;
      console.log ('Not empty' + $scope.movieListID)
    })
    .catch(function(response) {
      console.log ('No search reposone')
    });
}

但是控制台日志在“Response OK”后显示“未定义”消息。

1 个答案:

答案 0 :(得分:1)

尝试更改此

$scope.addMovie = function() {

addMovie.add().then(function(response){
  if(response){
    console.log ('Response')
  } else {
    console.log ('No reposone')
  }
});

到此:

$scope.addMovie = function() {

addMovie.add()
    .then(function(response){
        console.log ('Response OK');
    })
    .catch(function(responce){
        console.log ('Response error');
    });
像这样,你实际上正在捕捉你工厂/服务中可能发生的任何错误......