Javascript 等待$http完成,以便在AngularJS中输出结果
我如何使用函数等待$http请求完成 我的Javascript 等待$http完成,以便在AngularJS中输出结果,javascript,angularjs,oop,Javascript,Angularjs,Oop,我如何使用函数等待$http请求完成 我的services.js如下所示: var app=angular.module('starter.services',[]) 我的controllers.js看起来像: var app = angular.module('starter.controllers', []); app.controller('DealCtrl', function($scope, Deals) { $scope.deals = Deals.all(); c
services.js
如下所示:
var app=angular.module('starter.services',[])
我的controllers.js
看起来像:
var app = angular.module('starter.controllers', []);
app.controller('DealCtrl', function($scope, Deals) {
$scope.deals = Deals.all();
console.log($scope.deals);
});
我的controllers.js
文件中的console.log
输出“未定义”,但当我在getDeals()
函数中输出交易时,它包含从服务器获得的正确数组
我做错了什么?
$http
,angularjs中的所有异步服务都返回一个promise
对象。看
您需要使用然后
方法将其分配给范围中的值
因此,您的控制器:
app.controller('DealCtrl', function($scope, Deals) {
Deals.all().then(function (deals) {
$scope.deals = deals;
console.log($scope.deals);
});
});
你的服务
app.factory('Deals', function($http) {
function getDeals() {
return $http.get('http://www.domain.com/library/fct.get_deals.php')
.success(function (data) {
var deals = data;
return deals;
});
}
return {
all: function() {
return getDeals();
},
get: function(keyID) {
//...
}
}
});
感谢您的回答,但此代码引发以下错误:
TypeError:无法读取未定义的属性“then”
@JohnBrunner您需要在服务中将承诺返回给调用者。更新代码非常感谢。现在我没有错,但我还有一个问题。我的服务器数组看起来像[{id:“1”,title:“title”,…},…]
,但我无法使用ng repeat=“deal in deals”
和{{deal.title}}
@JohnBrunner访问title
,很高兴我帮了忙。如果您认为此问题已得到回答,请单击答案旁边的复选图标进行标记。但是,评论不是提出后续问题的合适地方,因为它对未来的访问者没有用处,我建议您尝试自己调试它,参考官方文档,如果其他一切都失败了,打开另一个问题。
app.factory('Deals', function($http) {
function getDeals() {
return $http.get('http://www.domain.com/library/fct.get_deals.php')
.success(function (data) {
var deals = data;
return deals;
});
}
return {
all: function() {
return getDeals();
},
get: function(keyID) {
//...
}
}
});