Search code examples
angularjsangularjs-service

What's the best way to determine my service is done loading & processing a HTTP get request?


I've got a service in Angular JS which basically performs a HTTP GET & some post-processing like so:

angular.module('myApp')
  .service('graphDataService', function($http) {
    this.getGraphData() {
      $http.get('http://localhost:32105/chartData')
        .then(function(result) {
          // Perform post processing here   
        });
    };
  });

What's the best way to communicate with my controller that the GET request and post-processing is complete? I've attempted creating a this.doneLoading variable within my service but I can't access it from the asynchronous code.

I'm still rather new at Angular so any suggestions or criticism would be greatly appreciated. Thanks!


Solution

  • $http.get() returns a promise which you then call .then() upon. I think the proper solution is to have the service return the promise rather than notify the caller.

    Here's more information on how these promises work

    In case you need to do post-processing in your service you should create your own promise and return it like A.B showed in his example. :)