0

I have problem related AngularJS dependency injection and timing between them. Here is my code and error

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

module.factory('demo', function () {
        return {
            data: {},
        };
    });

module.provider('foo', ['demo', function(demo) {
    console.log(demo);

    this.$get = function() {
    };
}]);

Error:

Uncaught Error: [$injector:modulerr] Failed to instantiate module Demo due to:
Error: [$injector:unpr] Unknown provider: demo

But if I add setTimeout on last definition everything works fine, but its hacking code it shouldn't be like this.

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

module.factory('demo', function () {
        return {
            data: {},
        };
    });
setTimeout(function(){
module.provider('foo', ['demo', function(demo) {
    console.log(demo);

    this.$get = function() {
    };
}]);

});

Here is problem on fiddle: http://jsfiddle.net/zcf7rb4s/1/

0

2 Answers 2

1

You cannot add demo as a dependency there because it does not yet exist. That's the way the $injector works. What you can do is list demo as a dependency in the $get function of the provider. That's going to be executed by the $injector after all providers have been defined.

Check this:

<div ng-app="Demo">
    <div ng-controller="test">{{x}}</div>
</div>

And the definitions:

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

module.factory('demo', function () {
        return {
            data: {x: 'x'},
        };
    });

module.provider('foo', function() {
    this.$get = function(demo) {
        return {
            demo: demo
        };
    };
});

module.controller('test', ['$scope', 'foo', function($scope, foo) {
    $scope.x = foo.demo.data.x;
}]);

The code inside the factory and provider is run at "step 1". Then, in "step 2" AngularJS binds the controller. It first uses $injector to inject the dependencies (that have been previously defined in "step 1"). So in practice your $timeout "emulates" this behavior, that's why it works. But it's wrong, that's not the way you are supposed to use them.

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

Comments

0

Inject into the provider like this instead:

module.provider('foo', function() {
    this.$get = ['demo', function(demo) {
        console.log(demo);
    }];
});

Comments

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.