Configurable Service in AngularJS

30 / Mar / 2015 by Vibhor Kukreja 1 comments

Angular provide services for handling non-view logic, communication with server(back-end) and can holds data & state. These services are singleton objects that can be used to share and organize code. For doing so, angular provides us five cool ways to make a service on the bases of once need.

Following are the five approaches that can be used to create a service in angular:

1) Value

app.value('name', 'Vibhor Kukreja');

2) Constant

app.constant('name', 'Vibhor Kukreja');

3) Factory

app.factory('myService', function(){
        return{
              getName: function() {
                       return 'Vibhor Kukreja';
                       }
              }
});

4) Service

app.service('myService', function() {
       var name = 'Vibhor Kukreja';
       this.myName = function() {
                      return name;
                    }
});

5) Provider

app.config(function($provide){
		$provide.provider('myService', function(){
			return {
				$get: function() {
					return {
						name: 'Vibhor Kukreja'
						}
					}
				}
		});
});

All these approaches have their own key use cases. Depending upon the use case, one can pick an approach to implement a service.

The main focus of the blog is on the Provider approach of Angular Services.

The provider approach allows us to make a service from a much lower level, which makes the service to be configurable. In this, we have a function that returns an object with a function named $get.
The angular calls this $get function once to create your service(since it is singleton) at the start application

Now, we can configure the service with the provider approach before it gets created.

app.config(function($provide){
	$provide.provider('myService', function(){
		var msg;
		return {
			myConfig: function(greet) {
					msg = greet;
			},
			$get: function() {
				return {
					name: msg + ' Vibhor Kukreja'
					}
				}
			}
	});
});

app.config(function (myServiceProvider)) {
	myServiceProvider.myConfig('Hello');
}

The thing that we need to remember is that, the $get function is only called once, at the time of application configuration phase. And once you have used the service on run-time then you can’t re-configure it.

Hope this will help.

FOUND THIS USEFUL? SHARE IT

comments (1 “Configurable Service in AngularJS”)

  1. Amit Thakkar

    Nice blog :-) .

    We can create provider with “module.provider()” api. And we use
    Providers for making apis,
    Services are used when we are playing with single singleton object
    and factory for multiple singleton objects..

    Reply

Leave a comment -