1

I got an error TypeError: Cannot read property 'success' of undefined when using $http and my custom service.

My app.js :

app.controller('AppCtrl', ['$scope', '$http', 'topicContent', function($scope, $http, topicContent){

  topicContent.request().success(function(data){
    $scope.threadContent = data;
    console.log(data);
  });

}]);

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

    var query = function() {
        return
          $http({
            url: "http://www.corsproxy.com/daysof.me/lowyat/thread.php",
            method: "GET"
        });
    }

    return {
        request : function(){
            return query();
        }


    }
}]);

This is so strange, I couldn't find any flaw of it.

Alex wood
  • 163
  • 2
  • 12

1 Answers1

0

The problem is that this code

var query = function() {
    return
      $http({
        url: "http://www.corsproxy.com/daysof.me/lowyat/thread.php",
        method: "GET"
    });
}

is equivalent to this one:

var query = function() {
    return;
      $http({
        url: "http://www.corsproxy.com/daysof.me/lowyat/thread.php",
        method: "GET"
    });
}

due to automatic semicolon insertion in javascript. Note that there is semicolon ; after return. So the solution is to move $http to the same line after return statement:

return $http({ ... });

Read about in what situations javascript interpreter inserts semicolon ; automatically, for example here. In your case after return interpreter will insert ; which makes query function return undefined. Hence the error you are getting.

Community
  • 1
  • 1
dfsq
  • 182,609
  • 24
  • 222
  • 242