Sunday, 21 January 2018

Creating and using a service in Angular js

AngularJS services allow you to share code throughout your application, thanks to what is called dependency injection.
AngularJS offers a large number of ready-to-use services (and providers). These are preceded by the $ symbol. Here are some examples:
  • $ timeout
  • $ http
  • $ compiles
If you are new to AngularJS, and before using a method provided by jQuery (randomly), always ask yourself if the framework does not offer a solution. So, to make an Ajax query, prefer to use $ http rather than jQuery.ajax () . In the first case we remain in the domain of AngularJS, in the second case, the view will not be automatically updated on receipt of the data (not instantly anyway).
AngularJS services are:
  • Lazily instantiated, that is to say, instantiated only when we need it
  • Of singletons, that is to say, they are instantiated only once (not once import)
Here are some examples of use:
  • Recover data via Ajax requests (instead of doing it everywhere in the controllers)
  • Group "utilities" functions that can be useful everywhere in your application
  • Define the parameters of your application (eg development / production mode ...)

Example of creating and using a service

index.html

<! doctype html>
<html lang = "en" ng-app = "myApp">
 <Head>
  <meta charset = "UTF-8">
  <title> The services </ title>
 </ Head>
<Body>

 <div ng-controller = "MainCtrl">
  <P> {{userData.firstName}} </ p>
  <P> {{userData.userName}} </ p>
  <P> {{userData.age}} </ p>
 </ Div>

 <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"> </ script>
 <script src = "app.js"> </ script>
</ Body>
</ Html>

app.js

var app = angular.module ("myApp", []);

/ * Main controller
================================================== * /

app.controller ("MainCtrl", ["$ scope", "userService",
 function ($ scope, userService) {
  $ scope.userData = userService.getUserData ();
 }
]);

/ * A first service
================================================== * /

app.service ("userService", ["utilsService", "$ timeout",
 function (utilsService, $ timeout) {
  // Private variable
  var userData = {
   firstName: "natasha",
   userName: "nat31",
   age: 25
  };

  // Getter for the userData variable
  this.getUserData = function () {
   // This method uses another service
   userData.firstName = utilsService.capitalize (userData.firstName);
   return userData;
  };

  // 5 seconds after loading the page, the value of a property changes in the service.
  // The view is updated automatically
  $ timeout (function () {
   userData.userName = "NATNAT";
  }, 5000);
 }
]);

/ * A second service
================================================== * /

app.service ("utilsService", [
 function () {
  this.capitalize = function (str) {
   // Credit: http://stackoverflow.com/a/1026087/962893
   return str.charAt (0) .toUpperCase () + str.slice (1);
  };
 }
]);


Explanation of the code

The view is content to display the contents of the userData variable of the controller, nothing very complicated:
<div ng-controller = "MainCtrl">
 <P> {{userData.firstName}} </ p>
 <P> {{userData.userName}} </ p>
 <P> {{userData.age}} </ p>
</ Div>
The special feature of this application is that the controller uses a service ( userService ) to retrieve the data:
app.controller ("MainCtrl", ["$ scope", "userService",
 function ($ scope, userService) {
  $ scope.userData = userService.getUserData ();
 }
]);
Note that it would have been possible to give the view direct access to userService, but it would not have been very elegant :(:
$ scope.userService = userService;
The declaration of a service is similar to that of a controller. Like a controller, it can take as parameter other services, it is what is called the injection of dependencies . However, you will notice that there is no $ scope parameter , because a service is not directly related to the view.
app.service ("userService", ["utilsService", "$ timeout",
 function (utilsService, $ timeout) {

 }
]);
The data is here hard, but we could recover them via an Ajax request thanks to the $ http service :
// Private variable
var userData = {
 firstName: "natasha",
 userName: "nat31",
 age: 25
};
Since the function has been declared with  this , it is public, so it is accessible from other controllers, services ... as long as the service is injected .
Note also that this service uses another service to capitalize the first letter of the  firstName :
// Getter for the userData variable
this.getUserData = function () {
 // This method uses another service
 userData.firstName = utilsService.capitalize (userData.firstName);
 return userData;
};
Finally, 5 seconds after loading the page, the value of a property changes in the service, but since it is in the AngularJS domain , the view is updated automatically. The change would not have been instantaneous if we had used setTimeout (Javascript):
$ timeout (function () {
 userData.userName = 'NATNAT';
}, 5000);
Note that $ timeout is also a service
Also Read About

8 comments:

  1. Hi admin, your blog lots of information and I have learned to create and use a service in angular. Share more like this.
    Angularjs Training in Chennai | Angularjs course in Chennai | Angularjs Training institute in Chennai

    ReplyDelete
  2. I am really impressed the way you have written the blog. Hope we are eagerly waiting for such post from your side. HATS OFF for the valuable information shared!
    AngularJS Training in Chennai

    ReplyDelete
  3. Your blog left the readers with some kind of useful info. Have been waiting for more updates from this blog admin. Do share more.

    IELTS Coaching in Mulund
    IELTS Training in Mulund West
    IELTS Courses in Mulund
    IELTS Coaching Centres in Mulund
    IELTS Centres in Mulund East

    ReplyDelete
  4. This comment has been removed by the author.

    ReplyDelete