AngularJS:服务调用API并返回JSON

AngularJS: Service call API and return JSON

本文关键字:返回 JSON API 调用 服务 AngularJS      更新时间:2023-09-26

我需要使用服务从视图的输入字段传递一个值。服务应该调用我的WebAPI2,然后接收一个有效的JSON作为响应。

然而,我要么得到一个承诺对象,我无法解决(即使有".then()"),或者如果我使用一个工厂,它不会编译,因为它似乎没有实现$get方法。

我返回的JSON对象也是有效的。

视图:

<div class="input" ng-controller="InputController as ctrl">
<input ng-model="inputdata" /> {{inputdata}}
    <button ng-click="ctrl.gibDaten(inputdata)">Senden</button>
    {{cooledaten}}
</div>

控制器:

module GoogleMapsApp {
myApp.myAppModule.controller("InputController",
    ["$scope", "mapsServiceCustom",
        function ($scope, mapsServiceCustom) {
            $scope.lEingabedaten = $scope.inputdata;
            this.gibDaten = function () {
                $scope.cooledaten = mapsServiceCustom.gibDaten().then();
                console.log($scope.cooledaten);
            }
}]);

}

服务:

module GoogleMapsApp {
myApp.myAppModule.service("mapsServiceCustom",
    ["$http",
        function ($http) {
            this.gibDaten = function (lEingabe) {
                console.log(lEingabe);
                console.log($http.get("api/getDistanceData/" + lEingabe + "/Cologne")
                    .then(function(data) {
                        return data;

控制器:}));返回http美元。get("api/getDistanceData/" + lEingabe + "/Cologne").then(function (data) {返回数据;});//返回http美元。get("api/getDistanceData/" + lEingabedaten1 + "/Cologne");}}

]);

}

控制台日志:

对象{$$state: Object}maps. servicecstomm .js:14:17

Object {$$state: Object}InputController.js:8:17

如果我检查$$state:对象,它包含了所需的数据。

使用factory会导致以下错误:

https://docs.angularjs.org/error/$喷射器/undef ? p0 = mapsServiceCustom

我做错了什么?我该如何实现我的意图?

你需要传递一个函数给那个部分…因此,只需将该函数放入控制器并将返回响应设置为变量。

myApp.myAppModule.controller("InputController",
    ["$scope", "mapsServiceCustom",
        function ($scope, mapsServiceCustom) {
            $scope.lEingabedaten = $scope.inputdata;
            this.gibDaten = function () {
                mapsServiceCustom.gibDaten().then(function(response){
                    // set response to your variable
                    $scope.cooledaten = response;
                });
            }
}]);

您没有正确实现该服务。请点击以下链接(Angularjs官方文档)https://docs.angularjs.org/guide/services

你需要通过返回一个js对象来公开你的API。(同样的事情显示在你的错误链接。请同时参考)
module GoogleMapsApp {
myApp.myAppModule.service("mapsServiceCustom",
    ["$http", function ($http) {
            this.gibDaten = function (lEingabe) {
                console.log(lEingabe);
                console.log($http.get("api/getDistanceData/" + lEingabe + "/Cologne")
                    .then(function(data) {
                        return data;
                    }
            }
            return { gibDaten: this.gibDaten};
    }]);
}
在这里你可以了解更多关于$get的信息方法https://docs.angularjs.org/guide/providers