How to make controller wait for promise to resolve from angular service

情到浓时终转凉″ 提交于 2019-12-23 07:11:45

问题


I have a service that is making an AJAX request to the backend

Service:

    function GetCompaniesService(options)
    {
        this.url = '/company';
        this.Companies = undefined;
        this.CompaniesPromise = $http.get(this.url);

    }

Controller:

var CompaniesOb = new GetCompanies();
CompaniesOb.CompaniesPromise.then(function(data){
   $scope.Companies = data;
});

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?


回答1:


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

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



回答2:


There is no problem to achieve that!

The main thing you have to keep in mind is that you have to keep the same object reference (and in javascript arrays are objects) in your service.

here is our simple HTML:

<div ng-controller = "companiesCtrl"> 
  <ul ng-repeat="company in companies">
     <li>{{company}}</li>
  </ul>
</div>

Here is our service implementation:

serviceDataCaching.service('companiesSrv', ['$timeout', function($timeout){
  var self = this;

  var httpResult = [
    'company 1',
    'company 2',
    'company 3'
  ];

  this.companies = ['preloaded company'];
  this.getCompanies = function() {
    // we simulate an async operation
    return $timeout(function(){
      // keep the array object reference!!
      self.companies.splice(0, self.companies.length);

      // if you use the following code:
      // self.companies = [];
      // the controller will loose the reference to the array object as we are creating an new one
      // as a result it will no longer get the changes made here!
      for(var i=0; i< httpResult.length; i++){
        self.companies.push(httpResult[i]);
      }
      return self.companies;
    }, 3000);                    
}}]);   

And finally the controller as you wanted it:

serviceDataCaching.controller('companiesCtrl', function ($scope, companiesSrv) {
  $scope.companies = companiesSrv.companies;
  companiesSrv.getCompanies();
});

Explanations

As said above, the trick is to keep the reference between the service and the controller. Once you respect this, you can totally bind your controller scope on a public property of your service.

Here a fiddle that wraps it up.

In the comments of the code you can try uncomment the piece that does not work and you will see how the controller is loosing the reference. In fact the controller will keep having a reference to the old array while the service will change the new one.

One last important thing: keep in mind that the $timeout is triggering a $apply() on the rootSCope. This is why our controller scope is refreshing 'alone'. Without it, and if you try to replace it with a normal setTimeout() you will see that the controller is not updating the company list. To work around this you can:

  • don't do anything if your data is fetched with $http as it calls a $apply on success
  • wrap you result in a $timeout(..., 0);
  • inject $rootSCope in the service and call $apply() on it when the asynchronous operation is done
  • in the controller add a $scope.$apply() on the getCompanies() promise success

Hope this helps!




回答3:


You can pass the $scope into GetCompanies and set $scope.Companies to the data in the service

 function GetCompaniesService(options,scope)
 {
    this.url = '/company';
    this.Companies = undefined;
    this.CompaniesPromise = $http.get(this.url).then(function(res) {
      scope.Companies = res;
    });

 }

You have to be careful about the order in which you then use the data. That's kind of the reason behind a promise to begin with.



来源:https://stackoverflow.com/questions/25899717/how-to-make-controller-wait-for-promise-to-resolve-from-angular-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!