UI router Unknown provider for injecting service into child state resolve

15,186

Solution 1

In your controller you have to inject your service MyService, so define something like this

  .state('wizard.step1', {
    url: '/step1',
    templateUrl: ... ,
    resolve: {
      name: ['myService', function(myService) {
        // do something with mySerice
      }]
    },
    controller: ['name', function(name) {
      // controller codes here
    }]
  })

Solution 2

You have to inject your service in your config function :

var app = angular.module('app', ['services', 'ui.router']);
app.config(['$stateProvider', '$urlRouterProvider', 'myService',
          function($stateProvider, $urlRouterProvider, myService) {
...

Another way is to embed your resolve code in a service and assign directly the service :

app.config(['$stateProvider', '$urlRouterProvider' ,'mySuperService',function($stateProvider, 

    $urlRouterProvider, mySuperService) {
    ...
    resolve: {
     name: mySuperService()
    }


.constant('mySuperService', function() {

   var serv= function(){
      // your code
   }
   return serv;
}
Share:
15,186
Yujun Wu
Author by

Yujun Wu

Updated on June 28, 2022

Comments

  • Yujun Wu
    Yujun Wu almost 2 years

    Got Unknown provider when injecting service into the child state resolve function. But if defined a resolve in the parent state, it just works. Below there are some sample codes:

    I defined a service module

    angular.module('services', [])
      .factory('myService', function() {
        // my service here
      })
    

    and initialize the app

    var app = angular.module('app', ['services', 'ui.router']);
    app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, 
    
        $urlRouterProvider) {
          $stateProvider.state('wizard', {
            url: '/wizard',
            abstract: true
          })
          .state('wizard.step1', {
            url: '/step1',
            templateUrl: ... ,
            resolve: {
              name: function(myService) {
                // do something with mySerice
              }
            },
            controller: function(name) {
              // controller codes here
            }
          })
        }]);
    

    I got the error Unknown provider complaining about myService in the wizard.step1 resolve. But if I add a random resolve in the parent state, like

    $stateProvider.state('wizard', {
                url: '/wizard',
                abstract: true,
                resolve: {
                  a: function() { return 1; }
                }
              })
    

    then it works without error. Wonder what happens here?