我正在关注承诺的this Angular
教程。我有一个检查数组是否为空的服务,如果是,则命中REST
服务,返回一个promise并更新数组。这是相关代码:
requestingProviders: [],
getRequestingProviders: function() {
var that = this;
var deferred = $q.defer();
if(this.requestingProviders.length === 0) {
this.getResource().search({
role: 'REQUESTING_PROVIDER'
}, function(data) {
that.requestingProviders = data.providers;
deferred.resolve(data.providers);
});
return deferred.promise;
} else {
return that.requestingProviders;
}
}
service
正在调用controller
。以下是调用它的代码:
$scope.providers = providerService.getRequestingProviders();
进行REST
调用并返回正常,但视图永远不会更新。这不像教程解释的那样工作。 Here是一个能够展示我期待的东西。我做错了什么?
答案 0 :(得分:2)
你需要解决你的承诺:
var prom = providerService.getRequestingProviders();
prom.then(function (data) {
$scope.providers = data;
});
此外,将代码更改为始终返回承诺:
getRequestingProviders: function() {
var that = this;
var deferred = $q.defer();
if(this.requestingProviders.length === 0) {
this.getResource().search({
role: 'REQUESTING_PROVIDER'
}, function(data) {
that.requestingProviders = data.providers;
deferred.resolve(data.providers);
});
} else {
deferred.resolve(that.requestingProviders);
}
return deferred.promise;
}