Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS use custom services in custom providers

Tags:

angularjs

I have a simple question about the dependency injection in Angular. I create custom services in order to use them within each other. Unfortunately I receive errors the way I was trying it. 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] Failed to instantiate module app due to: [$injector:unpr] Unknown provider: $service1 http://errors.angularjs.org/1.2.0-rc.2/$injector/unpr?p0=%24service1

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

like image 470
user2911527 Avatar asked Oct 23 '13 13:10

user2911527


2 Answers

The code is mostly right, except you have to inject service dependencies in $get, not in the provider constructor function, like this:

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;
    }];
});
like image 83
Buu Nguyen Avatar answered Oct 20 '22 10:10

Buu Nguyen


It appears that provider can not inject such a dependency. If you rewrite $service2 using a 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

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

like image 35
Juliane Holzt Avatar answered Oct 20 '22 11:10

Juliane Holzt