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

Axschech picture Axschech · Sep 17, 2014 · Viewed 34.2k times · Source

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?

Answer

M.K. Safi picture M.K. Safi · Sep 17, 2014

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