我将在我的应用程序中使用 AngularJS 服务,并使一切变得干净漂亮。为此我遵循了一些文章。但它似乎还没有完成。对吧??
我没有看到任何错误或其他东西,但是当我设置警报(数据)时;我会收到未定义的错误。我错过了什么工作要做?
我的App.js
var app = angular.module('starter', ['ionic'])
我的Service.js
var serverPath = 'http://url/api/locations';
app.service('testService', function($http) {
this.getLocations = function() {
$http.get(serverPath).success(function(data) {
return data;
});
};
});
我的controller.js
app.controller('LocationsController', function ($scope, testService) {
$scope.locations = testService.getLocations();
});
和我的用户界面
<div ng-controller="LocationsController">
<ul>
<li ng-repeat="location in locations">
{{ location.locationName }}
</li>
</ul>
</div>
最佳答案
请求数据后,无法直接从异步调用中获取数据。您应该遵循 Promise 模式来处理异步数据。
我想指出你犯的几个错误。
- 您应该从服务方法
getLocations
返回$http.get
promise ,以便您可以将.then
函数放置在该方法上。 然后在 Controller 内部从 Controller 调用服务方法
getLocations
并放置.then
函数,其中第一个将在 ajax 成功时被调用,第二个将被调用关于ajax错误。.then
的函数this.getLocations = function () { return $http.get(serverPath); //return promise object };
Controller
testService.getLocations().then(function(response){ //success function
$scope.locations = response.data;
}, function(error){ //error function
console.log("Some error occurred", error)
});
关于javascript - 在 AngularJs 服务中从 Web Api 接收数据时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35491009/