jensengar
jensengar

Reputation: 6167

Access Provider from Service

Is it possible to access a provider that would normally be used in a config from a service? The reason for doing so is I don't have the information I need yet to be able to do it in the module.config.

The provider I would like to access is the $stateProvider which is part of the ui.router module. Lets say I have a module that is dependent on other modules. I would like to be able to have these dependencies register their "desired" routes/states with a service and then use the service determine which ones I actually register. I was hoping that this wouldn't have to be done in the config since I would effectively only be adding new states, not removing or modified those that are already there. So basically, I want my service to get a list of states/routes and have the service register them rather than doing it in the config.

Upvotes: 1

Views: 732

Answers (2)

Andyrooger
Andyrooger

Reputation: 6746

As commented:

You won't be able to inject a provider after the config phase. However you can inject during the config phase and store the it somewhere until you need it.

For example

app.config(function($stateProvider) {
    window.stateProvider = $stateProvider;
});

app.service('myService', function() {
    var $stateProvider = window.state provider;
    // ...
});

Disclaimer(s)

Though I am suggesting this as a possibility, I am certainly not recommending it. It will make your code hard to test, and I doubt it's officially supported so there's no guarantee the provider will work even if you can access it.

That said, if you need to do this and it works then so be it. Just be sure to test vigorously! :)

Upvotes: 2

tennisgent
tennisgent

Reputation: 14201

I've never used the ui.router module, but I believe it has to be setup in the config because the routes have to be setup before the app is initiated. From my understanding, it works basically the same as the $routeProvider, in that you have to setup everything you want to do in the config.

Its not explicitly said anywhere (that I can see), but the docs/examples found here seem to suggest that the $routeProvider can only be accessed from within a module declaration (ie app.module('myMod', [], function($routeProvider){ ... })) or inside of the app.config function.

I'm going to guess that the $stateProvider acts the same way.

Upvotes: 1

Related Questions