无法在Angular中发送带有$ http的POST请求 - ReferenceError:$ http未定义

时间:2015-03-07 10:59:20

标签: angularjs angular-http

所以我一直得到这个ReferenceError: $http is not defined,即使我在控制器中包含$http,这似乎是此错误消息的最常见原因。我还尝试将$ http传递给函数本身,但这并没有解决它。

我觉得我错过了一些非常明显的东西,所以任何帮助都会非常感激,谢谢!

为了清楚起见,我已经包含了整个脚本。您可以在finaliseDay函数内查看脚本末尾的发布请求。

谢谢!

这是错误:

ReferenceError: $http is not defined
    at l.$scope.finaliseDay (http://localhost:8888/goalzy.js:69:12)
    at ib.functionCall (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:198:303)
    at Dc.(anonymous function).compile.d.on.f (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:214:485)
    at l.$get.l.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:125:305)
    at l.$get.l.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:126:6)
    at HTMLAnchorElement.<anonymous> (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:215:36)
    at HTMLAnchorElement.c (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:32:389)angular.js:11607 (anonymous function)angular.js:8557 $getangular.js:14502 $get.l.$applyangular.js:21440 (anonymous function)angular.js:3014 c

这是HTML第一个

<!doctype html>
<html ng-app="goalzy">
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js"></script>
      <script src="goalzy.js"></script>
   </head>
   <body>
      <div class="container">
         <div class="well">
            <h2>Goalzy</h2>

            Dev TODO
            <ul>
               <li>Hook up the API to persist data</li>
            </ul>

            <div ng-controller="TodoController">
               <span>{{remaining()}} of {{todos.length}} remaining today</span>
               <span>You're at {{percentComplete()}}% completion</span>
               [ <a href="" ng-click="finaliseDay(percentComplete())">finalise day</a> ]
               <ul class="unstyled">
                  <li ng-repeat="todo in todos">
                     <input type="checkbox" ng-model="todo.done">
                     <span class="done-{{todo.done}}">{{todo.text}}</span>
                  </li>
               </ul>
               <form ng-submit="addTodo()">
                  <input type="text" ng-model="todoText"  size="30"
                     placeholder="add new todo here">
                  <input class="btn-primary" type="submit" value="add">
               </form>
               <hr>
               <div class="historial" ng-repeat="h in historicalDailyPercentages">
                  <ul>
                    <li>Date: {{h.date}}</li>
                    <li>Percentage of Daily Tasks Completed: {{h.percent}}%</li>
                    <li><div>Tweet it!</div></li>
                  </ul>

               </div>
            </div>
         </div>
      </div>
      </div>
   </body>


</html>

这是JS:

// Goalzy.js

angular.module('goalzy', [])

 .config(['$httpProvider', function($httpProvider) {
      $httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
   });

  .controller('TodoController', ['$scope','$http', function($scope, $http) {
$scope.todos = [];

$scope.historicalDailyPercentages = [];

$scope.addTodo = function() {

  if ($scope.todoText != "") {
    if ($scope.todos.length < 3) {
        $scope.todos.push({text:$scope.todoText, done:false});
        $scope.todoText = '';   

      //Save to DB

    }
    else {
        alert("You can only have 3 todos per day!");
      $scope.todoText = '';
    }   
  } else {
    alert("you must write something");
  }

};

$scope.remaining = function() {
  var count = 0;
  angular.forEach($scope.todos, function(todo) {
    count += todo.done ? 0 : 1;
  });
  return count;
};

$scope.percentComplete = function() {
    var countCompleted = 0;
    angular.forEach($scope.todos, function(todo) {
      countCompleted += todo.done ? 1 : 0; //Simply calculates how many tasks have been completed
    console.log(countCompleted);
    });

  var totalCount = $scope.todos.length;
  var percentComplete = countCompleted / totalCount * 100;
  return percentComplete;
}


$scope.finaliseDay = function(percentComplete) {
    alert("You're finalising this day with a percentage of: " + percentComplete);
    var today = new Date();
    var alreadyPresent = $scope.historicalDailyPercentages.some(function (item) { 
        return item.date.getFullYear() === today.getFullYear() &&
               item.date.getMonth() === today.getMonth() &&
               item.date.getDate() === today.getDate();
    });

    //Confirm that nothing has alreayd been posted for today
    if (!alreadyPresent) {
        $scope.historicalDailyPercentages.push({
            percent: percentComplete,
            date: today
        });

        // Simple POST request example (passing data) :
        $http.post('/api/postDailyPercentage.php', {msg:'hello word!'}).
          success(function(data, status, headers, config) {
            // this callback will be called asynchronously
            // when the response is available
            console.log("data" + data);
          }).
          error(function(data, status, headers, config) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
            console.log("data" + data);
          });

    }
    else {
      alert("You're all set for today - see you tomorrow!");
    }

    console.log($scope.historicalDailyPercentages);
}


  }]);

2 个答案:

答案 0 :(得分:2)

提供商无法在带有后缀&#39;提供商&#39;的控制器内使用,您只能通过提供商名称访问它们,此处仅$http,同时删除; } 配置初始化后

$httpProvider设置应在角配置阶段

内完成

<强> CODE

angular.module('goalzy', [])
.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
}]);
 .controller('TodoController', ['$scope', '$http', function($scope, $http) {
    //controller code here
}]);

注意:请务必从控制器中删除$httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';

Working Plunkr

答案 1 :(得分:0)

您不必在控制器中使用“$ httpProvider”,而是使用$ http。

e.g。

$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

作为最佳做法,请勿在控制器中配置提供程序($ http)。在配置部分中执行此操作。如下

    var app = angular.module('goalzy', []);
    app.config(function ($httpProvider) {
        $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
    });

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

        $scope.title="scope title";
        //$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
}]);

使用您的html查看http://run.plnkr.co/plunks/4mY4izqc48P8wVQFumZ8/的工作内容。