Service is a very important concept in angularjs, although we have a controller, but considering that its life is really fragile, we need to use the service.
service
when I first used it, I tied it up with service
factory()
a natural connection.
Indeed, factory()
it is the simplest way to create a service, but the service is not the only one.
Here is a note of my simple understanding of the service.
Service
A very important point--the service is a singleton .
A service is instantiated only once in a ANGULARJS application $injector
and communicates with vulnerable controllers throughout the application's lifecycle.
The most common way to register a service starts with registering a service factory()
.
Like what:
var myApp = angular.module(‘myApp‘,[]).factory(‘myService‘,function() { return {};});
factory()
Returns a service in the form of an object or function.
Let's try to inject $http
a service into MyService and write something like that.
PS: Find some URLs are not very ideal, I have to learn other people's demo, from GitHub to get the user's activity log information)
Injection? The same is true of injecting services into the controller, and putting the name of the service into the parameter list is injected, but it's just a simple way.
OK, let's change the MyService first:
.factory(‘myService‘,function($http) { return { getUserActivities: function(username){ return $http({ method: ‘JSONP‘, url:‘https://api.github.com/users/‘+username+‘/events?callback=JSON_CALLBACK‘ }); } };})
Depending on the user name entered, the output activity information is as follows:
<div ng-controller="myController"> <input type="text" ng-model="username" /> <table border="1"> <tr> <th></th> <th>user</th> <th>to</th> <th>at</th> </tr> <tr ng-repeat="activity in activities"> <td></td> <td>{{ activity.actor.login }} </td> <td>{{ activity.repo.name }}</td> <td>{{activity.created_at}}</td> </tr> </table></div>
We need $watch
this variable, but it's important to note that if the request frequency exceeds the limit, GitHub will give you a 403.
So you also need to $timeout
control the frequency of requests, a period of time to repeat the request to kill the previous.
The controller invokes the service code as follows:
.controller(‘myController‘,function($scope,myService,$timeout,$log){ var timeout; $scope.$watch(‘username‘,function(){ if(timeout){ $timeout.cancel(timeout) $log.info(‘timeout:::‘+timeout); } timeout= $timeout(function(){ myService.getUserActivities($scope.username) .success(function(response, status, headers, config){ $scope.activities = response.data; }) .error(function(response, status, headers, config){ $log.info(status) })},1000); });})
factory()
registering a service does not seem so complicated.
In fact, we have 5 ways to create a service:
- Factory
- Service
- constant
- Value
- Provider
Factory
In the simplest way, the function receives 2 parameters
- Name (string): Service Name
- GETFN (Function/array): Call this function when Angularjs instantiates a service
Service
Maybe it's more semantic, I like it better than factory()
that service()
.
The service also receives 2 parameters, respectively:
- Name (string): Service Name
- Constructor (function): constructor for a service object
Try to use the service()
following:
.service(‘myService‘,function($http) { this.getUserActivities = function(username){ return $http({ method: ‘JSONP‘, url:‘https://api.github.com/users/‘+username+‘/events?callback=JSON_CALLBACK‘ }); }})
Constant and value
These two names feel more unconventional, their parameters are the same:
Only semantically, if the method of the service $get
simply returns a constant, these two methods do fit.
May try to write a function in, if only the definition of the error will not be.
But there will be no corresponding provider, and the call will also prompt that the service is not a function and so on.
So, honestly, use this:
.constant(‘serviceId‘,‘00001‘)
What is the difference between the two?
The difference is that config()
when injected, take the above serviceId
as an example.
If Serviceid is a constant
, we can inject Serviceid into config (), but it cannot be serviceIdProvider
injected into config (), but it is value
just the opposite.
Provider
provider()
Is the most primitive method.
We tried factory()
provider()
to compare it with creating the same service.
.factory(‘aService‘,{ ‘name‘:‘a‘}).provider(‘bService‘,{ $get: {‘name‘:‘b‘}})
In other words factory()
, the second parameter is equivalent to the one $get
.
provider()
Receive two parameters:
- Name (String): is still the name of the service instance, if name+ ' Provider ' is the name of Provider.
- Provider (object/array/function): Not a service, is a provider with $get ()
$provide
The service initializes the provider at run time and invokes the creation of the $injector
$get
service instance.
So why use it instead of the provider()
other way around? The point is config()
that if we share a service with multiple applications, but before injecting the service to a service that is injected into different applications, it needs to be set in config () through the provider of the service, such as adding a decorator
anything.
Decorator
is to decorate the service, add features or completely change the service.
decorator()
Receive two parameters
- Name (string): The name of the service to decorate
- DECORATORFN (function): Called by the function when the service is instantiated
$injector
.
The following is an example of how the output is time-consuming after obtaining user activity information:
.config(function(myServiceProvider,$provide){ $provide.decorator(‘myService‘,function($delegate,$log) { var activities = function(username) { var startedAt = new Date(); var activities = $delegate.getUserActivities(username); activities.finally(function() { $log.info("Fetching activities" +" took " +(new Date() - startedAt) + "ms"); }); return activities; }; return {getUserActivities:activities}; });})
AngularJS-Service Introduction