Angular ajax 使用 $http 失败

Angular ajax failed using $http

本文关键字:http 失败 使用 ajax Angular      更新时间:2023-09-26

我在使用 $http 和我的自定义服务时TypeError: Cannot read property 'success' of undefined出错。

我的应用.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();
        }

    }
}]);

这太奇怪了,我找不到任何缺陷。

问题是这段代码

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

相当于这个:

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

由于在JavaScript中自动插入分号。请注意,return 后有分号;。因此,解决方案是在语句之后$http移动到同一行return

return $http({ ... });

阅读有关在什么情况下 javascript 解释器自动插入分号;的信息,例如这里。在您的情况下return解释器将插入;,这使query函数返回undefined。因此,您遇到的错误。