如何使控制器等待承诺从角度服务中解决 [英] How to make controller wait for promise to resolve from angular service
问题描述
我有一个向后端发出AJAX请求的服务
I have a service that is making an AJAX request to the backend
服务:
function GetCompaniesService(options)
{
this.url = '/company';
this.Companies = undefined;
this.CompaniesPromise = $http.get(this.url);
}
控制器:
var CompaniesOb = new GetCompanies();
CompaniesOb.CompaniesPromise.then(function(data){
$scope.Companies = data;
});
我希望我的服务处理".then"函数而不是必须在我的控制器中处理它,并且我希望能够在服务内部的诺言之后,让我的控制器对来自该服务的数据进行处理已解决.
I want my service to handle the ".then" function instead of having to handle it in my controller, and I want to be able to have my controller act on that data FROM the service, after the promise inside the service has been resolved.
基本上,我希望能够像这样访问数据:
Basically, I want to be able to access the data like so:
var CompaniesOb = new GetCompanies();
$scope.Companies = CompaniesOb.Companies;
在服务本身内部处理承诺的解决方案.
With the resolution of the promise being handled inside of the service itself.
这可能吗?还是我只能从服务外部访问该诺言的解决方案?
Is this possible? Or is the only way that I can access that promise's resolution is from outside the service?
推荐答案
如果只想处理服务本身中$http
的响应,则可以在要执行更多操作的服务中添加then
函数然后从该then
函数处理return
,如下所示:
If all you want is to handle the response of $http
in the service itself, you can add a then
function to the service where you do more processing then return
from that then
function, like this:
function GetCompaniesService(options) {
this.url = '/company';
this.Companies = undefined;
this.CompaniesPromise = $http.get(this.url).then(function(response) {
/* handle response then */
return response
})
}
但是您仍将在控制器中使用Promise,但是您返回的内容将已在服务中得到处理.
But you'll still have use a promise in the controller, but what you get back will have already been handled in the service.
var CompaniesOb = new GetCompanies();
CompaniesOb.CompaniesPromise.then(function(dataAlreadyHandledInService) {
$scope.Companies = dataAlreadyHandledInService;
});
这篇关于如何使控制器等待承诺从角度服务中解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!