Kunal Tyagi
Kunal Tyagi

Reputation: 55

Unable to fetch value from the service inside the controller

I just want to fetch the value of movies variable in the controller "Data Controller". Below is my code snippet for 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');
            }]);

From service "datatransfer", it is returning the correct value of movies but when the service is injected to controller and getMovies() is used, then it gives the below error. It is unable to take up the value being returned by the 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)

Thanks in advance.

Upvotes: 1

Views: 50

Answers (1)

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41377

Just return the http request from the service

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

catch the promise in the controller using then

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

Upvotes: 1

Related Questions