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

[code language=”javascript”]app.value(‘name’, ‘Vibhor Kukreja’);[/code]

2) Constant

[code language=”javascript”]app.constant(‘name’, ‘Vibhor Kukreja’);[/code]

3) Factory

[code language=”javascript”]app.factory(‘myService’, function(){
return{
getName: function() {
return ‘Vibhor Kukreja’;
}
}
});[/code]

4) Service

[code language=”javascript”]app.service(‘myService’, function() {
var name = ‘Vibhor Kukreja’;
this.myName = function() {
return name;
}
});[/code]

5) Provider

[code language=”javascript”]app.config(function($provide){
$provide.provider(‘myService’, function(){
return {
$get: function() {
return {
name: ‘Vibhor Kukreja’
}
}
}
});
});[/code]

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.

[code language=”javascript”]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’);
}[/code]

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.

Read Further on AngularJS Series

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 Reply

Your email address will not be published. Required fields are marked *