Services

The role services play in an Angular application is clear, but there can be confusion around the creation of services. This is because there are three very similar ways to create a service in Angular. We will look at each of these and why they should be used.

A service in Angular is an object that can be an authority on data (meaning it is the only source of some data). A great example is the route provider as it is the only object that provides route information. It is a singleton that all modules utilize, a way to keep data in sync between controllers, or all of these! A great example of a service that you will most likely need is $http. It makes AJAX requests for you. You can build a service that returns data from your API and you do not have to worry about creating AJAX calls in each and every controller.

Another example is the $route and $routeParams services. When you have a reference to the $route service, you can always find out what route has been matched. The $routeParams service will let you know the parameters.

Services should be used anytime you have the need to write the same code more than once. You can pull it out and put it into a service. In addition to this, services should be created for any data that will be used by more than one controller. The controller can then ask the service for the data. This will keep this data the same across multiple controllers.

All of the functions listed can be called from the module or off the $provide injectable object.

Factory, service, and provider will all rely on an HTML template of this:

<div ng-controller="SimpleController">
  {{ service }}
</div>

Factory

This is the method to create factories:

module.factory(name, getFunction)

Parameters

  • name(string): This is the name that the service will be known by. This can be used for dependency injection.
  • getFunction(function or array): This is the function that will return the service. This can also be an array that lists the dependencies.

Return value

This is an Angular module object.

Description

The service factory is great when you need a singleton. No configuration other than what is done in the factory() function is done. The object will be the same each time it is injected.

Here is a simple example that will return the name of the service. The example also creates a dependency on $http:

firstModule.factory('firstFactory', ['$http', function ($http) {
  var serviceName = 'firstFactory';
  return {
    getName: function(){return serviceName;}
  };
}]);

Service

Services can be initialized with new keyword:

module.service(name, constructor)

Parameters

  • name(string): This is the name of the service
  • constructor(function or array): This will be the function that is called as the constructor

Return value

This is an Angular module object.

Description

The key distinction between a service and a factory is that it can be initialized with new. Here is an example that depends on $http:

firstModule.service('firstService', ['$http', function ($http) {
  return function (name) {
    var serviceName = name;

    this.getName = function () {
      return serviceName;
    };
  };
}]);

Here is the controller that will initialize the service:

firstModule.controller('SimpleController', ['$scope', 'firstService', function ($scope, firstService) {
  var first = new firstService('First Service Name');
  var second = new firstService('Second Service Name');
  $scope.service = second.getName();
}]);

Provider

The function that provides the most control of the setup of a provider:

module.provider(name, provider)

Parameters

  • name(string): This is the name of the provider
  • provider(function or array)

Return value

This is an Angular module object.

Description

This is the final and most complex way to build a service. It must return an object with a $get method. You should use this when you must have this object ready for configuration. This is the only provider that can be injected during the configuration phase of application startup. The word "provider" will be appended to the name of this. For example, if you named your provider my, it will be injected using myProvider. Here is an example provider that has its name injected during configuration. First up is the provider definition:

firstModule.provider('first', function () {
  var serviceName;

  return {
    configSet: function (name) {
      serviceName = name;
    },
    $get: function () {
      return {
        getName: function () { return serviceName; }
      };
    }
  }
});

Next is the configuration. Notice how it is injected using firstProvider:

firstModule.config(['firstProvider', function (firstProvider) {
  firstProvider.configSet('firstProvider123');
}]);

Finally, here is the controller:

firstModule.controller('SimpleController', ['$scope', 'first', function ($scope, firstProvider) { 
  $scope.test = firstProvider.getName();
}]);

Value

This sets a value in the module:

module.value(name, value)

Parameters

  • name(string): This is the name of the value
  • value(object): This can be anything

Return value

This is an Angular module object.

Description

A value is something that is set and then can be injected later. Values can only be injected into a controller or service, not during configuration.

Here is a simple example of value:

firstModule.value('appTitle', 'First App');

Constant

This creates a constant variable in a module:

module.constant(name, value)

Parameters

  • name(string): This is the name of the value
  • value(object): This can be anything

Return value

This is an Angular module object.

Description

This is very similar to value, except that this can be used in the config function and that the value cannot be decorated.

Here is a simple example of constant:

firstModule.constant('appTitle', 'First App');

$http

This is the service used to make HTTP calls:

$http(config)

Parameters

  • config(object): This object has the following properties:
    • method(string): This is the HTTP method.
    • url(string): This is the URL.
    • params(string or object): This is the params for the request. An object will be mapped key to value for this.
    • data(string or object): This is the data to be sent in the request.
    • headers(object): This sets the headers for the request.
    • xsrfHeadername(string): This is the name of the header for XSRF.
    • xsrfCookieName(string): This is the name of the cookie for XSRF.
    • cache(Boolean): This is used to decide whether to cache data or not.
    • responseType(string): This is used to decide what the request type will be.

Return value

A promise will be returned.

Description

If you are familiar with jQuery's AJAX function, then you are familiar with this. This is Angular's way of making any XMLHttpRequests. For most things, you will use one of the convenience methods that make using $http easier.

Convenience methods

You can use all of the HTTP methods as functions: GET, POST, HEAD, PUT, DELETE, and PATCH. We will just look at GET, POST, and JSONP closely.

Note

GET, POST, and JSONP will cover most, if not all, of many people's needs for $http. If this does not, view the $http documentation at https://docs.angularjs.org/api/ng/service/$http.

Each function will take the URL as the first parameter and a config object, which is the same config object that $http() gets.

GET

This is a GET request:

$http.get(url, config)

Description

This executes a simple GET request. Here is an example of a factory that uses $http.get:

Here is the factory:

firstModule.factory('httpService', ['$http', function ($http) {
  return {
    test: function () { return $http.get('test', {params: 'test'}); }
  }
}]);

This returns a promise that the controller can then use:

firstModule.controller('SimpleController', ['$scope', 'httpService', function ($scope, httpService) {
  httpService.test().success(function (data, status) {
    console.log(data);
  })
  .error(function (data, status) { console.log('An error occured');});
}]);

POST

This is a POST request:

$http.post(url, config)

Description

This will make a POST request. Here is a factory that makes a POST and an example that uses localhost. Remember that you must be running a server that responds to POST requests for this to work:

firstModule.factory('httpService', ['$http', function ($http) {
  return {
    test: function () { return $http.post('http://localhost/post', { data: 'HEY' }); }
  }
}]);

jsonp

When you have to make a cross origin request, you should use JSONP. This will allow you to use the data instead of the request being blocked based on security.

Notable services

I will list out some useful services that can be injected, with a short blurb about each:

  • $anchorScroll: This parameter allows you to scroll to the element in the hash
  • $animate: This parameter allows DOM manipulations
  • $cacheFactory: This allows caching
  • $http: See $http
  • $interval: This uses Angular's way to call setInterval
  • $location: This gets the information about window.location
  • $rootScope: This returns the root scope for the application
  • $route: See Routing
  • $q: This allows promises to be added in our project
  • $timeout: This uses Angular's way to call setTimout

This is not a comprehensive list as Angular has many services and can create and include more. These are the ones that you will most likely use in your applications.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.93.132