2017-08-09 64 views
1

我只想在控制器“数据控制器”中获取影片变量的值。下面是我对app.js代码片段:无法从控制器内的服务中获取值

myApp.service('datatransfer', ['$http', function($http) 
     { 
      var service = this; 
      var movies; 
      service.getMovies = function() 
      { 
       $http.get('https://api.myjson.com/bins/54jf7').success(function(data) 
       { 
        movies = data; 
       }); 
       return movies; 
      }; 
     }]); 

     myApp.controller('DataController', ['$scope', '$http', '$location', 'datatransfer', function($scope, $http, $location, datatransfer) 
      { 
       $scope.loaded = false; 
       datatransfer.getMovies().then(function(data) 
       { 
        $scope.movies = data; 
        $scope.loaded = true; 
       }); 
       $location.path('/home'); 
      }]); 

从服务“数据传递”,它返回影片的正确值,但是当服务被注入控制器和getMovies()被使用,那么它给低于错误。它无法占用getMovies()返回的值。

angular.js:13642 TypeError: Cannot read property 'then' of undefined 
    at new <anonymous> (app.js:47) 
    at Object.invoke (angular.js:4708) 
    at P.instance (angular.js:10177) 
    at n (angular.js:9096) 
    at g (angular.js:8459) 
    at g (angular.js:8462) 
    at angular.js:8339 
    at angular.js:1782 
    at m.$eval (angular.js:17378) 
    at m.$apply (angular.js:17478) 

在此先感谢。

回答

1

单从服务中使用then

datatransfer.getMovies().then(function(response) { 
    $scope.movies = response.data; 
    $scope.loaded = true; 
}); 
+0

呀,“”然后“”应该与$承诺,是用来返回HTTP请求

myApp.service('datatransfer', ['$http', function($http) { var service = this; var movies; service.getMovies = function() { return $http.get('https://api.myjson.com/bins/54jf7') } }]); 

捕捉到控制器的承诺由$ http.get(...)返回。 – Maxwellt

+0

嘿@sachila,谢谢,现在工作。 –

+0

@Kunal Tyagi不错。请务必检查答案,如果这有帮助:D –