AngularJs ReferenceError:$ http未定义

Sab*_*kar 197 javascript-framework angularjs angular-http

我有以下Angular函数:

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

但无论什么时候调用这个函数,我都会进入ReferenceError: $http is not defined我的控制台.有人可以帮我理解我在做错了吗?

Łuk*_*man 370

可能你没有$http为你的控制器注入服务.有几种方法可以做到这一点.

请阅读有关DI的参考资料.然后它变得非常简单:

function MyController($scope, $http) {
   // ... your code
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!我想知道为什么Angular自己的文档(http://docs.angularjs.org/tutorial/step_05)有这个错误. (18认同)

Ami*_*arg 81

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

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

我已将上面的代码更改为以下内容.请记住包含$ http(2次),如下所示.

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

它运作良好.