无法从控制器

时间:2017-08-09 04:11:31

标签: angularjs

我只想在控制器“数据控制器”中获取电影变量的值。以下是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');
            }]);

从服务“datatransfer”,它返回正确的电影值但是当服务注入到控制器并且使用了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 个答案:

答案 0 :(得分:1)

只需从服务

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

使用then

捕获控制器中的承诺
datatransfer.getMovies().then(function(response) {
    $scope.movies = response.data;
    $scope.loaded = true;
});