Michael
Michael

Reputation: 13626

How to pass parameter from .run to .config?

I work on my angularjs ui-route project. in .run() core I put some variable in named clientid to $rootScope.

At some point I need to use stored variable in .config() core.

I know that I can't use $rootScope service in .config() core.

So my question is how to pass clientid variable from $rootScope to .config().Maybe I can use any another service?

Upvotes: 1

Views: 85

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136174

Ofcourse, using $rootScope would be wrong decision. Because no one prefers to pollute global scope and there are other reasons as well. You could consider creating an constant called as settings and utilize that in wherever you needed in any angular components like .run block, config phase, service, provider, etc.

angular.module('mainModule').constant('settings', {
   clientId: 1123 //some inital value
})

Though you could override this value from your config phase.

angular.module('mainModule').config(['settings', configFn])

function configFn(settings){
    //routes registers here

    //other awesome stuf

    //set clientId here
    //Assuming your clientId will be available, no async operation.
    if(someValue === 1)
      settings.clientId = 'asd12';  
    else
      settings.clientId = 'asd34';  
}

Thereafter you can use that constant inside your run block

angular.module('mainModule').run(['settings', runBlock])

function runBlock(settings){
   console.log(settings);
}

Note: The reason behind selecting constant is, this flavor can be available as injectable in any angular components.

Upvotes: 3

Related Questions