如何让控制器等待 Angular 服务的承诺解决 [英] How to make controller wait for promise to resolve from angular service

查看:22
本文介绍了如何让控制器等待 Angular 服务的承诺解决的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个向后端发出 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"函数,而不必在我的控制器中处理它,并且我希望能够让我的控制器在服务内部的 promise 之后处理来自服务的数据已解决.

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 函数到你做更多处理的服务,然后 return 从那个 then 函数,像这样:

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;
});

这篇关于如何让控制器等待 Angular 服务的承诺解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆