1

Is there a way for me to call a method on an object returned by a module during the start-up of my AngularJS application?

Here is my module:

angular.module('features', [])
    .factory('features', ['cookies', 'lib', function(cookies, lib) {
        return {
            init: function() {
                lib.customer(cookies.get('customer')).then(function (enabled) {
                    this.feature = enabled;
                });
            },

            feature: false,
        };
}]);

In my app.js file, if I had something similar to:

var app = angular
    .module('app', [
        'features'
    ]);

How could I then do something like: features.init()

So that later on, I can just use features.feature to get the boolean value of the key-value pair?

1 Answer 1

2

As written, the factory creates a race condition between its initialization and its use in controllers.

Rewrite it to return a promise:

angular.module('features', [])
.factory('features', ['cookies', 'lib', function(cookies, lib) {
    var enabledPromise = init();
    return {
        enabled: function() {
            return enabledPromise;
        }
    };
    function init() {
         return (
             lib.customer(cookies.get('customer'))
             .then(function(enabled) {
                 console.log(enabled)
                 return enabled;
              }).catch(function(error) {
                 console.log(error);
                 throw error;
              })
         );
     }
}]);

Usage

features.enabled().then(function(enabled) {
    console.log(enabled);
});

The service can also be used in the resolve function of a router to delay the loading of a view.

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, succinct, amazing. Thank you, and bravo :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.