The $provide service has a number of methods for registering components with the $injector. Many of these functions are also exposed on angular.Module
.
An Angular service is a singleton object created by a service factory. These service factories are functions which, in turn, are created by a service provider. The service providers are constructor functions. When instantiated they must contain a property called $get
, which holds the service factory function.
When you request a service, the $injector is responsible for finding the correct service provider, instantiating it and then calling its $get
service factory function to get the instance of the service.
Often services have no configuration options and there is no need to add methods to the service provider. The provider will be no more than a constructor function with a $get
property. For these cases the $provide service has additional helper methods to register services without specifying a provider.
$get
property will contain the given factory function.$get
property will instantiate a new object using the given constructor function.See the individual methods for more information and examples.
Register a provider function with the $injector. Provider functions are constructor functions, whose instances are responsible for "providing" a factory for a service.
Service provider names start with the name of the service they provide followed by Provider
. For example, the $log service has a provider called $logProvider.
Service provider objects can have additional methods which allow configuration of the provider and its service. Importantly, you can configure what kind of service is created by the $get
method, or how that service will act. For example, the $logProvider has a method debugEnabled which lets you specify whether the $log service will log debug messages to the console or not.
Param | Type | Details |
---|---|---|
name | string | The name of the instance. NOTE: the provider will be available under |
provider | Object function() | If the provider is:
|
Object |
registered provider instance |
The following example shows how to create a simple event tracking service and register it using $provide.provider().
// Define the eventTracker provider function EventTrackerProvider() { var trackingUrl = '/track'; // A provider method for configuring where the tracked events should been saved this.setTrackingUrl = function(url) { trackingUrl = url; }; // The service factory function this.$get = ['$http', function($http) { var trackedEvents = {}; return { // Call this to track an event event: function(event) { var count = trackedEvents[event] || 0; count += 1; trackedEvents[event] = count; return count; }, // Call this to save the tracked events to the trackingUrl save: function() { $http.post(trackingUrl, trackedEvents); } }; }]; } describe('eventTracker', function() { var postSpy; beforeEach(module(function($provide) { // Register the eventTracker provider $provide.provider('eventTracker', EventTrackerProvider); })); beforeEach(module(function(eventTrackerProvider) { // Configure eventTracker provider eventTrackerProvider.setTrackingUrl('/custom-track'); })); it('tracks events', inject(function(eventTracker) { expect(eventTracker.event('login')).toEqual(1); expect(eventTracker.event('login')).toEqual(2); })); it('saves to the tracking url', inject(function(eventTracker, $http) { postSpy = spyOn($http, 'post'); eventTracker.event('login'); eventTracker.save(); expect(postSpy).toHaveBeenCalled(); expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track'); expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track'); expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 }); })); });
Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get
property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider.
Param | Type | Details |
---|---|---|
name | string | The name of the instance. |
$getFn | function() Array.<(string|function())> | The injectable $getFn for the instance creation. Internally this is a short hand for |
Object |
registered provider instance |
Here is an example of registering a service
$provide.factory('ping', ['$http', function($http) { return function ping() { return $http.send('/ping'); }; }]);
You would then inject and use this service like this:
someModule.controller('Ctrl', ['ping', function(ping) { ping(); }]);
Register a service constructor, which will be invoked with new
to create the service instance. This is short for registering a service where its provider's $get
property is a factory function that returns an instance instantiated by the injector from the service constructor function.
Internally it looks a bit like this:
{ $get: function() { return $injector.instantiate(constructor); } }
You should use $provide.service(class) if you define your service as a type/class.
Param | Type | Details |
---|---|---|
name | string | The name of the instance. |
constructor | function() Array.<(string|function())> | An injectable class (constructor function) that will be instantiated. |
Object |
registered provider instance |
Here is an example of registering a service using $provide.service(class).
var Ping = function($http) { this.$http = $http; }; Ping.$inject = ['$http']; Ping.prototype.send = function() { return this.$http.get('/ping'); }; $provide.service('ping', Ping);
You would then inject and use this service like this:
someModule.controller('Ctrl', ['ping', function(ping) { ping.send(); }]);
Register a value service with the $injector, such as a string, a number, an array, an object or a function. This is short for registering a service where its provider's $get
property is a factory function that takes no arguments and returns the value service. That also means it is not possible to inject other services into a value service.
Value services are similar to constant services, except that they cannot be injected into a module configuration function (see angular.Module
) but they can be overridden by an Angular decorator.
Param | Type | Details |
---|---|---|
name | string | The name of the instance. |
value | * | The value. |
Object |
registered provider instance |
Here are some examples of creating value services.
$provide.value('ADMIN_USER', 'admin'); $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 }); $provide.value('halfOf', function(value) { return value / 2; });
Register a constant service with the $injector, such as a string, a number, an array, an object or a function. Like the value, it is not possible to inject other services into a constant.
But unlike value, a constant can be injected into a module configuration function (see angular.Module
) and it cannot be overridden by an Angular decorator.
Param | Type | Details |
---|---|---|
name | string | The name of the constant. |
value | * | The constant value. |
Object |
registered instance |
Here a some examples of creating constants:
$provide.constant('SHARD_HEIGHT', 306); $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']); $provide.constant('double', function(value) { return value * 2; });
Register a decorator function with the $injector. A decorator function intercepts the creation of a service, allowing it to override or modify the behavior of the service. The return value of the decorator function may be the original service, or a new service that replaces (or wraps and delegates to) the original service.
You can find out more about using decorators in the decorators guide.
Param | Type | Details |
---|---|---|
name | string | The name of the service to decorate. |
decorator | function() Array.<(string|function())> | This function will be invoked when the service needs to be provided and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments:
|
Here we decorate the $log service to convert warnings to errors by intercepting calls to $log.warn().
$provide.decorator('$log', ['$delegate', function($delegate) { $delegate.warn = $delegate.error; return $delegate; }]);
© 2010–2017 Google, Inc.
Licensed under the Creative Commons Attribution License 4.0.
https://code.angularjs.org/1.5.11/docs/api/auto/service/$provide