View source Improve this doc

$provide

service in module AUTO

Description

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.

  • provider(provider) - registers a service provider with the $injector
  • constant(obj) - registers a value/object that can be accessed by providers and services.
  • value(obj) - registers a value/object that can only be accessed by services, not providers.
  • factory(fn) - registers a service factory function, fn, that will be wrapped in a service provider object, whose $get property will contain the given factory function.
  • service(class) - registers a constructor function, class that that will be wrapped in a service provider object, whose $get property will instantiate a new object using the given constructor function.

See the individual methods for more information and examples.

Methods

  • constant(name, value)

Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see angular.Module#config) and it cannot be overridden by an Angular decorator.

Parameters

ParamTypeDetailsnamestring

The name of the constant.

value*

The constant value.

Returns

Object

registered instance

Example

Here a some examples of creating constants:

  1. $provide.constant('SHARD_HEIGHT', 306);
  2.  
  3. $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  4.  
  5. $provide.constant('double', function(value) {
  6. return value * 2;
  7. });
  • decorator(name, decorator)

Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service.

Parameters

ParamTypeDetailsnamestring

The name of the service to decorate.

decoratorfunction()

This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments:

  • $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to.

Example

Here we decorate the $log service to convert warnings to errors by intercepting calls to $log.warn().

  1. $provider.decorator('$log', ['$delegate', function($delegate) {
  2. $delegate.warn = $delegate.error;
  3. return $delegate;
  4. }]);
  • factory(name, $getFn)

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.

Parameters

ParamTypeDetailsnamestring

The name of the instance.

$getFnfunction()

The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}).

Returns

Object

registered provider instance

Example

Here is an example of registering a service

  1. $provide.factory('ping', ['$http', function($http) {
  2. return function ping() {
  3. return $http.send('/ping');
  4. };
  5. }]);

You would then inject and use this service like this:

  1. someModule.controller('Ctrl', ['ping', function(ping) {
  2. ping();
  3. }]);
  • provider(name, provider)

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.

Parameters

ParamTypeDetailsnamestring

The name of the instance. NOTE: the provider will be available under name + 'Provider' key.

providerObjectfunction()

If the provider is:

  • Object: then it should have a $get method. The $get method will be invoked using
  1. <a href="api/AUTO.$injector#invoke"><code>$injector.invoke()</code></a> when an instance needs to be
  2. created.
  • Constructor: a new instance of the provider will be created using
  1. <a href="api/AUTO.$injector#instantiate"><code>$injector.instantiate()</code></a>, then treated as
  2. `object`.
Returns

Object

registered provider instance

Example

The following example shows how to create a simple event tracking service and register it using $provide.provider().

  1. // Define the eventTracker provider
  2. function EventTrackerProvider() {
  3. var trackingUrl = '/track';
  4.  
  5. // A provider method for configuring where the tracked events should been saved
  6. this.setTrackingUrl = function(url) {
  7. trackingUrl = url;
  8. };
  9.  
  10. // The service factory function
  11. this.$get = ['$http', function($http) {
  12. var trackedEvents = {};
  13. return {
  14. // Call this to track an event
  15. event: function(event) {
  16. var count = trackedEvents[event] || 0;
  17. count += 1;
  18. trackedEvents[event] = count;
  19. return count;
  20. },
  21. // Call this to save the tracked events to the trackingUrl
  22. save: function() {
  23. $http.post(trackingUrl, trackedEvents);
  24. }
  25. };
  26. }];
  27. }
  28.  
  29. describe('eventTracker', function() {
  30. var postSpy;
  31.  
  32. beforeEach(module(function($provide) {
  33. // Register the eventTracker provider
  34. $provide.provider('eventTracker', EventTrackerProvider);
  35. }));
  36.  
  37. beforeEach(module(function(eventTrackerProvider) {
  38. // Configure eventTracker provider
  39. eventTrackerProvider.setTrackingUrl('/custom-track');
  40. }));
  41.  
  42. it('tracks events', inject(function(eventTracker) {
  43. expect(eventTracker.event('login')).toEqual(1);
  44. expect(eventTracker.event('login')).toEqual(2);
  45. }));
  46.  
  47. it('saves to the tracking url', inject(function(eventTracker, $http) {
  48. postSpy = spyOn($http, 'post');
  49. eventTracker.event('login');
  50. eventTracker.save();
  51. expect(postSpy).toHaveBeenCalled();
  52. expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  53. expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  54. expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  55. }));
  56. });
  • service(name, constructor)

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 the service constructor function that will be used to instantiate the service instance.

You should use $provide.service(class) if you define your service as a type/class. This is common when using CoffeeScript.

Parameters

ParamTypeDetailsnamestring

The name of the instance.

constructorFunction

A class (constructor function) that will be instantiated.

Returns

Object

registered provider instance

Example

Here is an example of registering a service using $provide.service(class) that is defined as a CoffeeScript class.

  1. class Ping
  2. constructor: (@$http)->
  3. send: ()=>
  4. @$http.get('/ping')
  5.  
  6. $provide.service('ping', ['$http', Ping])

You would then inject and use this service like this:

  1. someModule.controller 'Ctrl', ['ping', (ping)->
  2. ping.send()
  3. ]
  • value(name, value)

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.

Value services are similar to constant services, except that they cannot be injected into a module configuration function (see angular.Module#config) but they can be overridden by an Angular decorator.

Parameters

ParamTypeDetailsnamestring

The name of the instance.

value*

The value.

Returns

Object

registered provider instance

Example

Here are some examples of creating value services.

  1. $provide.value('ADMIN_USER', 'admin');
  2.  
  3. $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  4.  
  5. $provide.value('halfOf', function(value) {
  6. return value / 2;
  7. });