Angular Provider access in ui router

Issue

I tried changing service into a provider to get access config phase.
The provider is in other module.

var app = angular.module('ops.services');

app.constant('opsConstants', {
    GID: 'UA1'
});

app.provider('OpsConstantService', OpsConstantService);

OpsConstantService.$inject = ['opsConstants'];

function OpsConstantService(opsConstants) {
    return {
        $get:function() {
            return {
                OPSCONSTANTS : opsInsightConstants,
            }
        }
    }
}

My app module depends on the same, and DI has been provided.

var opsApp = angular.module('opsApp', ['ui.router',  'ops.services', 'angular-momentjs']);

And,now, In my app, routing I need to access the constants value.

opsApp.config(routerConfig);

routerConfig.$inject = ['$stateProvider', '$urlRouterProvider','OpsConstantServiceProvider'];

function routerConfig($stateProvider, $urlRouterProvider,OpsConstantServiceProvider) {
    $urlRouterProvider.otherwise("/home/dashboard/");

    $stateProvider
        .state('Modal', {
            url: .....

But if I try to log OpsConstantServiceProvider.OPSCONSTANTS it’s undefined.

Why so ?

What am I doing wrong ?

Solution

This works:

function OpsConstantService(opsConstants) {
    return {
        OPSCONSTANTS : opsInsightConstants,
        $get:function() {
            return {
                // something
            }
        }
    }
}

app.config(['OpsConstantServiceProvider', function(OpsConstantServiceProvider) {
  console.log(OpsConstantServiceProvider.OPSCONSTANTS);
}]);

But, this is not good)
Actually what are you trying to do? Gather constants and create one big object?
Then you can do this:

app.constant('test1', {test: 1});
app.constant('test2', {test: 2});
app.constant('test3', {test: 3});
app.constant('commons', {});

app.config(['test1', 'test2', 'test3', 'commons', function(test1, test2, test3, commons) {
  commons.test1 = test1;
  commons.test2 = test2;
  commons.test3 = test3;
}]);

Answered By – Petr Averyanov

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.