AngulaJS services
-
Upload
albert-cyberhulk -
Category
Software
-
view
519 -
download
0
Transcript of AngulaJS services
S E RV I C E S :
h t t p s : / / g i t h u b . c o m / a l b e r t s t e p a n y a n / a n g u l a r j s /t e c h t a l k s /
AngularJS-TechTalks
SERVICES
Up until now, we’ve only concerned ourselves with how the view is tied to $scope and how the controller manages the data. For memory and performance purposes, controllers are instantiated only when they are needed and discarded when they are not. That means that every time we switch a route or reload a view, the current controller gets cleaned up by Angular.
Services provide a method for us to keep data around for the lifetime of the app and communicate across controllers in a consistent manner. Services are singleton objects that are instantiated only once per app (by the $injector) and lazy- loaded (created only when necessary). They provide an interface to keep together those methods that relate to a specific function.
$http, for instance, is an example of an AngularJS service. It provides low-level access to the browser’s XMLHttpRequest object. Rather than needing to dirty the application with low-level calls to the XMLHttpRequest object, we can simply interact with the $http API.
angular.module('angularJsTechTalksApp', []) .factory(‘UserService', function($http) { var current_user; return { getCurrentUser: function() { //http get call here return current_user; }, setCurrentUser: function(user) { //http post call here current_user = user; } }});
// example service that holds on to the
// current_user for the lifetime of the app
There are several ways to create and register a service with the $injector. The most common and flexible way to create a service uses the angular.module API factory:
angular.module(CustomServices', []) .factory(‘UsersService', function() { // Our first service return serviceInstance; var serviceInstance = {}; return serviceInstance; });This service factory function is responsible for generating a single object or function that becomes this service, which will exist for the lifetime of the app.
REGISTERING A SERVICE
When our Angular app loads the service, the service will execute this function and hold on to the returned value as the singleton service object. The service factory function can be either a function or an array, just like the way we create controllers:
// Creating the factory through using the // bracket notation angular.module('myApp.services', [])angular.module('CustomServices') .factory(‘UsersService', [function($http, $log, $location) { var serviceInstance = {}; $log.info(serviceInstance); return serviceInstance; }]);
ARRAY STYLE
Now, anywhere that we need to access the GitHub API, we no longer need to call it through $http; we can call the githubService instead and let it handle the complexities of dealing with the remote service. To expose a method on our service, we can place it as an attribute on the service object. To use a service, we need to identify it as a dependency for the component where we’re using it: a controller, a directive, a filter, or another service. At run time, Angular will take care of instantiating it and resolving dependencies like normal. To inject the service in the controller, we pass the name as an argument to the controller function. With the dependency listed in the controller, we can execute any of the methods we define on the service object.
SERVICE USAGE
angular.module('CustomServices') .factory('UsersService', function($http, $log, $location, Request) { var baseUrl = 'http://ios7api.apiary-mock.com/users'; return { getUsers: function(cb) { Request.internalHttpRequest(baseUrl, 'get', function(data) { cb(data); }, {}, function(error) { cb(false); }); } }; });
LETS CODE SERVICE
angular.module('angularJsTechTalksApp') .controller('ServicesCtrl', function ($scope, $log, UsersService) { $scope.users = []; $scope._init_ = function() { UsersService.getUsers(function(data) { $log.info(data); if(data) { $scope.users = data; } }); }; $scope._init_(); });
LETS CODE CONTROLLER
While the most common method for registering a service with our Angular app is through the factory() method, there are some other APIs we can take advantage of in certain situations to shorten our code. The five different methods for creating services are:
• factory() • service() • constant()• value()• provider()
OPTIONS FOR CREATING SERVICES
While the most common method for registering a service with our Angular app is through the factory() method, there are some other APIs we can take advantage of in certain situations to shorten our code. The five different methods for creating services are:
• factory() • service() • constant()• value()• provider()
As we have already covered factory in details, we are passing straight to the .service() method
OPTIONS FOR CREATING SERVICES
If we want to register an instance of a service using a constructor function, we can use service(), which enables us to register a constructor function for our service object. The service() method takes two arguments:
• name (string)
This argument takes the name of the service instance we want to register. • constructor (function)
Here is the constructor function that we’ll call to instantiate the instance. The service() function will instantiate the instance using the new keyword when creating the instance.
.SERVICE()
"use strict";//Registering constructorvar Person = function($http) { this.getName = function() { return $http({ method: 'GET', url: '/api/user' }); };};
//Instantiating as new Serviceangular.service('personService', Person);
LETS CODE A SERVICE
These factories are all created through the $provide service, which is responsible for instantiating these providers at run time. A provider is an object with a $get() method. The $injector calls the $get method to create a new instance of the service. The $provider exposes several different API methods for creating a service, each with a different intended use. At the root of all the methods for creating a service is the provider method. The provider() method is responsible for registering services in the $providerCache. Technically, the factory() function is shorthand for creating a service through the provider() method wherein we assume that the $get() function is the function passed in. The two method calls are functionally equivalent and will create the same service.
.PROVIDER()
angular.module('CustomServices', []) .provider("UsersService", function () { this.baseUrl = null; this.setBaseUrl = function(url) { if (url) { this.baseUrl = url; } }; var self = this; this.$get = function(Request, $log) { return { getUsers: function(cb) { Request.internalHttpRequest(self.baseUrl, 'get', function (data) { cb(data); }, {}, function (error) { cb(false); }); } } }; });
LETS CODE A .PROVIDER()
It’s possible to register an existing value as a service that we can later inject into other parts of our app as a service. For instance, let’s say we want to set an apiKey for a back-end service. We can store that constant value using constant(). The constant() function takes two arguments: • name (string) This argument is the name with which to register the constant. • value (constant value) This argument gives the value to register as the constant. The constant() method returns a registered service instance.
angular.module('CustomProviders') .constant('apiKey', '123123123');
. CONSTANT()
If the return value of the $get method in our service is a constant, we don’t need to define a full- blown service with a more complex method. We can simply use the value() function to register the service. The value() method accepts two arguments: • name (string) Once again, this argument gives the name with which we want to register the value. • value (value) We’ll return this value as the injectable instance.The value() method returns a registered service instance for the name given.
angular.module('myApp') .value('apiKey', '123123123');
. VALUE()
The major difference between the value() method and the constant() method is that you can inject a constant into a config function, whereas you cannot inject a value. Conversely, with constants, we’re unable to register service objects or functions as the value. Typically, a good rule of thumb is that we should use value() to register a service object or function, while we should use constant() for configuration data.
angular.module('myApp', []) .constant('apiKey', '123123123') .config(function(apiKey) { // The apiKey here will resolve to 123123123 }) .value('FBid', '231231231') .config(function(FBid) { // error with Unknown provider: FBid because the value is not accessible by });
WHEN TO USE VALUE OR CONSTANT