Search code examples
jsonangularjsservicerootscope

Why is $http.get() undefined in my Angular service?


I'm trying to load some JSON and store it using $rootScope so that it persists between controllers. When I run my app I get the following error:

TypeError: Cannot call method 'get' of undefined

The get method was working perfectly until I tried to introduce $rootScope... any ideas?

My service looks like this:

  1 /**
  2  * Service to get the quiz data from a JSON source
  3  */
  4 app.factory('quizService', ['$rootScope', function ($scope, $rootScope, $http) {
  5     var promise;
  6     var service = {
  7         getQuiz: function($scope, $http) {
  8             if ( !promise ) {
  9                 promise = $http.get('QuizFileName.quiz').then(function (response) {
 10                     return response.data;
 11                 });
 12             }
 13             return promise;
 14         }
 15     };
 16     return service;
 17 }]);

My controller looks like this:

  7     // Get Quiz data from service
  8     quizService.getQuiz().then(function(data) {
  9         $scope.quiz = data;
 10
 11         // Redirect to scores if already completed this
 12         if($scope.quiz.complete === true) {
 13             $location.path('scores');
 14         }
 15     });

Solution

  • OK, Reboog711 put me on the right track, I needed to modify my factory definition to include $http, I had previously tried to do this, but mistakenly put it together like this:

    '$rootScope, $http'
    

    Don't do this, it's bad and wrong! But Reboog711's answer also gave me errors because I think you can't use $scope in the way we both thought.

    The correct (or working) solution was:

    app.factory('quizService', ['$rootScope', '$http', function ($rootScope, $http) {
    

    I hope this helps other newcomers to Angular. Many thanks to all who replied with their comments. I really respect this community for its great attitude to helping others :)