AngularJS uses user services in user providers

I have a simple question about dependency injection in Angular. I create custom services to use them in each other. Unfortunately, I get errors the way I tried to do this. This is my code:

var myApp = angular.module('app', []); myApp.service('$service1', ['$rootScope', function($rootScope) { this.test = function() { console.log('service1'); }; }]); myApp.provider('$service2', ['$service1', function($service1) { var service = 'service2'; this.registerService = function(mytext) { service = mytext; }; this.$get = function() { var that = {}; that.test = function() { console.log(service); }; return that; }; }]); myApp.config(['$service2Provider', function($service2Provider) { $service2Provider.registerService('changed service2'); }]); myApp.controller('AppCtrl', ['$rootScope', '$service1', '$service2', function($rootScope, $service1, $service2) { $service1.test(); $service2.test(); }]); 

Error: [$ injector: modulerr] Unable to create the module application because of: [$ injector: unpr] Unknown provider: $ service1 http://errors.angularjs.org/1.2.0-rc.2/ $ injector / unpr ? p0 =% 24service1

If you remove the dependency $servic1 in $service2 , it will work, but why?

+6
source share
2 answers

The code is mostly right, except that you must enter utility dependencies in $get , and not in the provider constructor function, for example:

 myApp.provider('$service2', function() { var service = 'service2'; this.registerService = function(mytext) { service = mytext; }; this.$get = ['$service1', function($service1) { var that = {}; that.test = function() { console.log(service); }; return that; }]; }); 
+2
source

It seems that provider cannot introduce such a dependency. If you rewrite $service2 using factory, it works:

 myApp.factory('$service2', ['$service1', function($service1) { var that = {}; that.test = function() { $service1.test(); console.log('service2'); }; return that; }]); 

See this plunker: http://plnkr.co/edit/JXViJq?p=preview

I also believe that service names begin with $ a, reserved for AngularJS and its extensions. Use names without $ at the beginning for services defined by your application.

+1
source

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


All Articles