我正在使用Ionic Framework 7 AngularJS构建应用程序
$ ionic info
Your system information:
Cordova CLI: 6.2.0
Gulp version: CLI version 3.9.1
Gulp local:
Ionic Framework Version: 1.2.4
Ionic CLI Version: 1.7.16
Ionic App Lib Version: 0.7.3
OS: Distributor ID: LinuxMint Description: Linux Mint 17.1 Rebecca
Node Version: v0.12.2
我构建的页面检索教会服务列表并将其显示在主详细信息列表中。所以我按照以下代码将$ http代码放在服务中:
services.js:
.service('ServicesService', ['$http', '$sce', function($http, $sce){
var services = [];
$http.get('http://demo0194057.mockable.io/services').then(function(response) {
services = response.data;
window.q = services; //checking value of services var
}, function(error) {
console.error("Error loading Services Endpoint! " + error);
});
return {
getAllServices: function() {
console.log('from inside return obj ' + services);
window.p = services; // checking value of services var
return services;
}
}
}])
controller.js:
.controller('servicesCtrl', function($scope, $http, ServicesService, InfoService) {
$scope.services = [];
$scope.services = ServicesService.getAllServices();
window.r = $scope.services;
$scope.doRefresh = function() {
$http.get('http://demo0194057.mockable.io/services').success(function(response) {
$scope.services = response;
})
.finally(function() {
// stop the ion-refresher from spinning
$scope.$broadcast('scroll.refreshComplete');
});
}
})
所以我的问题是该服务返回一个空数组而不是JSON REST API中的对象数组。我在代码中放了一些调试变量,我可以从控制器看到,服务返回一个空数组(var window.r)。在服务中,window.p也是空的,但window.q具有正确的对象数据,这意味着API调用正常工作。我无法弄清楚数据在哪里丢失,以至于它没有从服务中成功返回。
请帮忙
答案 0 :(得分:0)
在您的服务中,您需要在$http.get
方法的正文中执行getAllServices
请求。否则,get控件的then子句在控制器调用getAllServices
之后执行,这就是services
变量在该点初始化的原因。
答案 1 :(得分:0)
尝试这样:
<强>服务强>
.service('ServicesService', ['$http', '$sce', function($http, $sce){
var services = [];
return {
getAllServices: function() {
return $http.get('http://demo0194057.mockable.io/services').then(function(response) {
services = response.data;
return services;
}, function(error) {
console.error("Error loading Services Endpoint! " + error);
});
}
}
}]);
<强>控制器强>
.controller('servicesCtrl', function($scope, $http, ServicesService, InfoService) {
$scope.services = [];
$scope.doRefresh = function() {
ServicesService.getAllServices().then(function (response) {
$scope.services = response;
});
});
});
答案 2 :(得分:0)
$http.get('http://demo0194057.mockable.io/services').then(function(response) {
services = response.data;
window.q = services; //checking value of services var
}, function(error) {
console.error("Error loading Services Endpoint! " + error);
});
这是异步功能。所以services = response.data将在稍后执行。
$ scope.services = ServicesService.getAllServices();这将在角度上升之后调用,并且可能之前将执行异步执行。
因此。如果你不想得到你的服务,你必须包装你的ServicesService.getAllServices();作为承诺,您将等待第一次请求。但似乎存在一些架构问题......尝试将代码推迟一段时间并重新设置它。