繁体   English   中英

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

[英]AngularJs Error : $http request though defined in controller

我有以下代码,在其中我调用.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',函数($ HTTP){

您必须将$ http注入到使用它的服务getName中。

您也需要将其注入服务

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM