Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting error "Failed to instantiate module app due to unknown provider" with my custom provider

Tags:

angularjs

Trying to create custom provider and use it during app config. During configuration phase getting an error "Failed to instantiate module app due to unknown provider 'configRoutesProvider'". Provider code:

    (function () {
    'use strict';

    angular.module('app-routing', [])
        .provider('configRoutesProvider', function () {

            this.$get = ['$http', getRoutesProvider];

            function getRoutesProvider($http) {
                return {
                    getRoutes: function ($http) {
                        return $http.get('https://localhost:44311/api/account/routes').then(function (results) {
                            return results;
                        });
                    }
                };
            }
        });
}).call(this);

In app.js code get a reference to the 'app-routing' module:

(function () {
    'use strict';
    var app = angular.module('app',
            [
                'ngRoute',              // routing
                'LocalStorageModule',   // local storage

                'app-routing'
            ]);


        app.run();
})();

And in config.js when trying to reference the provider get the above error:

app.config(['$routeProvider', 'configRoutesProvider', routeConfigurator]);
    function routeConfigurator($routeProvider, configRoutesProvider) {
        var routes = configRoutesProvider.getRoutes();
        routes.forEach(function (r) {
            $routeProvider.when(r.href, {
                controller: r.controller,
                templateUrl: r.templateUrl
            });
        });
        $routeProvider.otherwise({ redirectTo: '/home' });

    }

In index.html the order of scripts registration is following:

<script src="app/routesProvider.js"></script>
<!-- Load app main script -->
<script src="app/app.js"></script>
<script src="app/config.js"></script>

Can't understand what I miss?

like image 797
Vladimir Avatar asked Feb 12 '23 06:02

Vladimir


1 Answers

In angular, providers doesn't have the provider part on its name, so the idea is to have:

angular.module('foo').provider('configRoutes', function() { });

and not:

angular.module('foo').provider('configRoutesProvider', function() { });

But when you inject it on a config, you have to put it:

angular.module('foo').config(function(configRoutesProvider) { });

So, in your example, remove the provider part on the definition.

like image 86
Jesus Rodriguez Avatar answered Mar 05 '23 18:03

Jesus Rodriguez