无法通过Angular服务进行后端呼叫

时间:2016-03-09 15:38:00

标签: angularjs rest

我是新手学习从我的角度应用程序的服务回拨结束电话,我正在从角度服务进行后端呼叫。

我从控制器调用服务中的函数。

我提供的其他服务不是我打的实际服务,由于某些原因我无法透露。我确信我所拥有的其他服务是有效的并且正在工作,因为我能够通过控制器点击它,这是一种不好的方式,所以这就是我想要将后端调用更改为服务。

以下是我的js文件。如果我做错了,请随时告诉我。

    angular.module("myApp",[])

    .controller("myCont", ['myService',  function($http, myService){

            var vm = this;
            this.myUrl = "some rest service";


            console.log("The  controller");

            vm.getDataInController = function() {
                console.log("The function is called");
                myService.getData(vm)
                    .success(function (custs) {
                        console.log("The data is obtained");
                    })
                    .error(function (error) {
                        console.log("some error occurred");
                    });
            }
        }])


        .service('myService', ['$http', function ($http) {

            this.getData = function (vm) {
                console.log("control is in the service");
                console.log(vm.myUrl);
                $http({
                    type: 'GET',
                    url: vm.myUrl
                    // data is where we have the JSON returned in the form of OBJECT from the gis
                }).then(function successCallback(response) {
                    console.log("the backend call worked");
                }), function errorCallback(response) {
                    console.log("the backend call worked");
                }

            };


    }])
    ;

我的Html文件是

<!DOCTYPE html>
<html >
<head lang="en">
    <meta charset="UTF-8">
    <title></title>

    <script src = "angular-min.js"></script>
    <script src = "sampleOneScript.js"></script>

</head>
<body ng-app = "myApp" ng-controller = "myCont as main">

{{main.myUrl}}

<br>


<button type = "button" ng-click = main.getDataInController()>Click me </button>

</body>
</html>

我在控制台中收到的错误。

TypeError:无法读取未定义的属性“getData”     在vm.getDataInController(http://localhost:63342/exercise.weokspce/ng-repeat%20example/sampleOneScript.js:15:26)     at fn(eval at(http://localhost:63342/exercise.weokspce/ng-repeat%20example/angular-min.js:212:87),:4:275)     在f(http://localhost:63342/exercise.weokspce/ng-repeat%20example/angular-min.js:252:82)     at m。$ eval(http://localhost:63342/exercise.weokspce/ng-repeat%20example/angular-min.js:132:366)     at m。$ apply(http://localhost:63342/exercise.weokspce/ng-repeat%20example/angular-min.js:133:60)     在HTMLButtonElement。 (http://localhost:63342/exercise.weokspce/ng-repeat%20example/angular-min.js:252:134)     在HTMLButtonElement.Hf.c(http://localhost:63342/exercise.weokspce/ng-repeat%20example/angular-min.js:35:137

1 个答案:

答案 0 :(得分:3)

问题可能是你没有正确注入&#34; myCont&#34;的所有依赖项。尝试更改行:

.controller("myCont", ['myService',  function($http, myService){

使用:

.controller("myCont", ['$http', 'myService',  function($http, myService){

并查看是否更正了事情

相关问题