[英]$q not updating when the GET request returns
I am following this Angular
tutorial on promises. 我正在遵循这个关于承诺的
Angular
教程。 I have a service that checks if an array is empty and if so, hits a REST
service, returns a promise and updates the array. 我有一个服务,检查数组是否为空,如果是,请点击
REST
服务,返回一个promise并更新数组。 Here is the relative code: 这是相关代码:
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;
}
}
The service
is being called from a controller
. 该
service
正在从controller
调用。 Here is the code where it is being called: 以下是调用它的代码:
$scope.providers = providerService.getRequestingProviders();
The REST
call is made and returns fine, but the view is never updated. REST
调用已生成并返回正常,但视图永远不会更新。 This is not working like the tutorial explained. 这不像教程解释的那样工作。 Here is a plunker that shows what I am expecting.
这是一个展示我期待的东西。 What am I doing wrong?
我究竟做错了什么?
You need to resolve your promise: 你需要解决你的承诺:
var prom = providerService.getRequestingProviders();
prom.then(function (data) {
$scope.providers = data;
});
Also, change your code to always return the promise: 此外,将代码更改为始终返回承诺:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.