简体   繁体   中英

How to inject '$urlRouterProvider' into factory?

I have followed this post How inject $stateProvider in angular application? and I have managed to figure out how to use '$stateprovider' but now I have issue with the '$urlRouterProvider' .

Does that mean I can't inject '$urlRouterProvider' into controller either and it should be only injected into config?

I highly appreciate any help any help on this issue.

There is a very narrowed snippet of the $urlRouterProvider code:

$UrlRouterProvider.$inject = ['$locationProvider', '$urlMatcherFactoryProvider'];
function $UrlRouterProvider( $locationProvider, $urlMatcherFactory) {

// I. config
// these are CONFIGURATION methods 
// we can access in .config() phase
....

this.rule = function (rule) {
  ...
}
...
this.when = function (what, handler) {
  ...
}

...
// II. application run
// this is the service/factory/configured provider 
// injected in the .run() phase via IoC

this.$get = $get;
$get.$inject = ['$location', '$rootScope', '$injector', '$browser'];
function $get( $location, $rootScope, $injector, $browser) {
  ...
  return {
    sync: function() {
      ...
    },
    listen: function() {
      ...
}

And this is the answer. In the config we do have access to configuration methods of the provider $urlRouterProvider . While later, in phase of application run, our services/factories are via IoC provided with the result of the configured $get()

For more details, see:

Configuring Providers

You may be wondering why anyone would bother to set up a full-fledged provider with the provide method if factory, value, etc. are so much easier. The answer is that providers allow a lot of configuration. We've already mentioned that when you create a service via the provider (or any of the shortcuts Angular gives you), you create a new provider that defines how that service is constructed. What I didn't mention is that these providers can be injected into config sections of your application so you can interact with them!

First, Angular runs your application in two-phases--the config and run phases. The config phase, as we've seen, is where you can set up any providers as necessary. This is also where directives, controllers, filters, and the like get set up. The run phase, as you might guess, is where Angular actually compiles your DOM and starts up your app.

In case, you need to access $stateProvider or $routeProvider configuration even later... there is a way... Check this plunker. Can hardly say that this is the angular way... but it is working. Check it here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM