AngularJS:服务调用API并返回JSON
AngularJS: Service call API and return JSON
我需要使用服务从视图的输入字段传递一个值。服务应该调用我的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 - Jquery:对返回JSON数据的php脚本的Ajax调用
- 返回JSON中的下标
- jQuery Map 从多个源返回 JSON 对象
- 如何在 Node.js 中返回 JSON 后停止代码流
- AngularJS:表单提交没有返回JSON中的值
- 使用ajax发送数据,返回json
- 从我的解析函数返回json
- 如何从脚本页面返回json数据
- 有些人有任何关于如何使用Modified Java Script Value处理返回Json(url)的示例
- 如何在html页面中从ajax返回json数据
- Ajax调用在本地返回json,但在服务器上运行时返回xml
- ajax调用返回JSON ParseError即使认为JSON看起来是正确的
- 调用.ajax方法得到未定义的json结果,返回json格式列表<字符串>
- 如何通过C#返回JSON并用JavaScript进行解析
- 使用 AJAX 返回 json 数组
- 从 AJAX 命令返回 JSON 格式的响应
- 如何通过node中的请求返回JSON.js(从javascript)
- Node.js API 在终端中返回 JSON,但不在浏览器中返回 JSON
- 如何在支柱 2 中返回 JSON 数组
- Rhino:从 Java 中返回 JSON