UI Router Unknown provider for injecting service into child state

Gets an unknown provider when the service is injected into the child state resolution function. But if a solution is defined in the parent state, it just works. The following are sample code:

I defined a service module

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

and initialize the application

 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 an error An unknown provider complaining about myService in wizard.step1 solution. But if I add a random solution in the parent state, for example

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

then it works without errors. I wonder what is going on here?

+5
source share
3 answers

In your controller, you must enter your MyService service, 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 }] }) 
+1
source

You must enter your service in your configuration function:

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

Another way is to insert the solution code into the service and assign the service directly:

 app.config(['$stateProvider', '$urlRouterProvider' ,'mySuperService',function($stateProvider, $urlRouterProvider, mySuperService) { ... resolve: { name: mySuperService() } .constant('mySuperService', function() { var serv= function(){ // your code } return serv; } 
+1
source

I have the same error. Try this code. It works great ...

  <script type="text/javascript"> var myApp = angular.module('myApp', ['ui.router']); myApp.config(['$stateProvider','$urlRouterProvider', function ($stateProvider, $urlRouterProvider) { $stateProvider. state('Page1', { url: '/Page1', templateUrl: 'Page1.html' }). state('Page2', { url: '/Page2', templateUrl: 'Page2.html' }) }]); </script> 
-1
source

Source: https://habr.com/ru/post/1203770/


All Articles