How to configure angular with a provider that needs async initialization?

I have a serviceProvider that requires some async init. I want my controllers to access this service only if init is complete.

angular.module("myModule").provider("AsyncInit", {
    myThing: {},
    init: function(options) {
        doSomeAsyncStuff(options).success(function(newThing) {
            myThing = newThing;
        });
    },
    $get: function() {
        return {
            theThing: myThing
        }
    }
});

//Initialisation of myModule 
angular.module(myModule)
    .config(function(AsyncInitProvider) {
        AsyncInitProvider.init(options);
    })

If I access the AsyncInit.theThingin the controller, it is not initialized first, but later. This seems logical to me.

Can I wait until the service is initialized?

+4
source share
1 answer

If you really need to start an asynchronous call in the process of setting up your provider, you can use $ interval.

this.$get = function($q, $interval) {
  var deferred = $q.defer();
  var handler = $interval(function() {
    if (myThingHasBeenLoaded) {
      $interval.cancel(handler);
      deferred.resolve(myThingsValue);
    }
  }, 100);

  return {
    getMyThing: function() {
      return deferred.promise();
    }
  };
}

// In your controller:
myThingService.getMyThing().then(function(myThing) { console.log(myThing); } );

API Google, . 100 , , . , 100 , 1 . , :

angular.module("myModule").provider("AsyncInit", function () {

  this.options = {};

  this.init = function(options) {
    this.options = options;
  };

  this.$get = function($q) {
    var deferred = $q.defer();
    var self = this;
    return {
      getMyThing: function() {
        doSomeAsyncStuff(self.options)
          .success(function(newThing) {
            deferred.resolve(newThing);
          })
          .failure(function(errors) {
            deferred.reject(errors);
          });

        return deferred.promise();  
      }
    };
  };
});

, .

+2

All Articles