AngularJs 错误:$http请求虽然在控制器中定义

AngularJs Error : $http request though defined in controller

本文关键字:控制器 定义 请求 错误 http AngularJs      更新时间:2023-09-26

我有以下代码,其中我调用.php服务来返回数据,这些数据稍后将更新我的模型和视图。虽然,我在控制器中注入了服务名称和http,但它仍然给我错误。

.HTML:

<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl"> 
    <button ng-click="changeIt()">Change Name</button>{{name}}
    <script>
        //Module declaration
        var app = angular.module('myApp',[]);
        //controller declaration
        app.controller('myCtrl', function($scope, getName, $http){
            $scope.name = "Peter"; 
            $scope.changeIt = function(){
                getName.getTheName()
                    .success(function(data) {
                        $scope.name = data.name;
                    });
            }
        });
        //Service Declaration
        app.service('getName',function(){
            return {
                getTheName: function() {
                    return $http({
                        url: 'hello.php',
                        method: 'Post',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });
                },
            }
        });
    </script>
</body> 
</html>

.PHP:

<?php
echo $data=json_encode(array('name'=>'Lara'));
?>

有人可以帮助我解决问题吗?

$http应该在服务中定义,而不是在控制器中定义

app.service('getName',function($http){

您也需要将其注入服务中

app.service('getName',function($http){
            return {
                getTheName: function() {
                    return $http({
                        url: 'hello.php',
                        method: 'Post',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });
                },
            }
        });
您必须在

服务中注入$http getName使用它。