【问题标题】:AngularJs ReferenceError: $http is not definedAngularJs ReferenceError: $http 未定义
【发布时间】:2012-11-25 09:32:00
【问题描述】:

我有以下 Angular 函数:

$scope.updateStatus = function(user) {    
    $http({
        url: user.update_path, 
        method: "POST",
        data: {user_id: user.id, draft: true}
    });
};

但每当调用此函数时,我的控制台中都会收到 ReferenceError: $http is not defined。有人可以帮我理解我在这里做错了什么吗?

【问题讨论】:

    标签: angularjs javascript-framework angular-http


    【解决方案1】:

    可能您还没有将$http 服务注入您的控制器。有几种方法可以做到这一点。

    请阅读this reference about DI。然后就很简单了:

    function MyController($scope, $http) {
       // ... your code
    }
    

    【讨论】:

    【解决方案2】:

    我在使用的时候也遇到了同样的问题

        myApp.controller('mainController', ['$scope', function($scope,) {
            //$http was not working in this
        }]);
    

    我已将上面的代码更改为下面给出的。请记住包含 $http(2 次),如下所示。

     myApp.controller('mainController', ['$scope','$http', function($scope,$http) {
          //$http is working in this
     }]);
    

    而且效果很好。

    【讨论】:

      【解决方案3】:

      只是为了完成Amit Garg answer,在AngularJS中注入依赖有几种方法。


      你也可以使用$inject添加依赖:

      var MyController = function($scope, $http) {
        // ...
      }
      MyController.$inject = ['$scope', '$http'];
      

      【讨论】:

        猜你喜欢
        • 2016-05-09
        • 2015-08-26
        • 2014-06-17
        • 2016-07-07
        • 1970-01-01
        • 2020-12-26
        • 1970-01-01
        • 2016-11-13
        • 2017-02-18
        相关资源
        最近更新 更多