Configurable Service in AngularJS
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
- AngularJS : A “Write Less Do More” JavaScript Framework
- AngularJS : Updating a Label Dynamically with User Input
- AngularJS : Adding Items to a JavaScript List and updating corresponding DOM Dynamically
- AngularJS : Text Suggestions
- AngularJS : Sorting objects on various attributes
- AngularJS : Fetching data from the server
- AngularJS : Multiple Views, Layout Template and Routing
- AngularJS : Implementing Routes And Multiple Views
- Building Intuitive Frontend Interfaces with AngularJS
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..