This article mainly talks about the introduction of custom services of angularjs. Some specific usage examples of custom services. Now let’s take a look at this article
3 ways to create custom services.
Factory
Service
Provider
Everyone should know that AngularJS was invented by backend staff in their spare time. He mainly applied the layered thinking that already existed in the backend. So we have to understand the role of layering. If you are a front-end person and don’t understand what layering is, then you’d better ask your back-end colleagues.
dao layer: It is the Model layer. When in the background, the role of this layer is to write the layer that interacts with the database. In angularJS, it is mainly used to write ajax.
Service layer: It mainly checks and writes logic code, but it can also persist data (acting as a data container) in angularJS for use by different controllers.
controller layer: The control layer, where controllers are written in angularJS. Try not to write unnecessary logic in the controller, and try to write it in the service layer.
So, there are three ways to create custom services.
The service created by factory method is to return a An object whose properties have methods. Equivalent to: var f = myFactory();
<!DOCTYPE html><html><head><meta charset="utf-8"><script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script></head><body><p ng-app="myApp" ng-controller="myCtrl"> <p>{{r}}</p></p><script> //创建模型 var app = angular.module('myApp', []); //通过工厂模式创建自定义服务 app.factory('myFactory', function() { var service = {};//定义一个Object对象' service.name = "张三"; var age;//定义一个私有化的变量 //对私有属性写getter和setter方法 service.setAge = function(newAge){ age = newAge; } service.getAge = function(){ return age; } return service;//返回这个Object对象 }); //创建控制器 app.controller('myCtrl', function($scope, myFactory) { myFactory.setAge(20); $scope.r =myFactory.getAge(); alert(myFactory.name); });</script></body></html>
In a custom serviceInject service example, but $scope scope objects cannot be injected.
<script> var app = angular.module('myApp', []); app.factory('myFactory', function($http,$q) { var service = {}; service.name = "张三"; //请求数据 service.getData = function(){ var d = $q.defer(); $http.get("url")//读取数据的函数。 .success(function(response) { d.resolve(response); }) .error(function(){ d.reject("error"); }); return d.promise; } return service; }); app.controller('myCtrl', function($scope, myFactory) { //alert(myFactory.name); myFactory.getData().then(function(data){ console.log(data);//正确时走这儿 },function(data){ alert(data)//错误时走这儿 });; }); </script>
Create a custom service through service method, which is equivalent to an object of new: var s = new myService() ;, only properties and methods added to this can be called in the controller. (If you want to see more, go to the PHP Chinese website AngularJS Development Manual to learn)
<p ng-app="myApp" ng-controller="myCtrl"> <h1>{{r}}</h1></p><script> var app = angular.module('myApp', []); app.service('myService', function($http,$q) { this.name = "service"; this.myFunc = function (x) { return x.toString(16);//转16进制 } this.getData = function(){ var d = $q.defer(); $http.get("ursl")//读取数据的函数。 .success(function(response) { d.resolve(response); }) .error(function(){ alert(0) d.reject("error"); }); return d.promise; } }); app.controller('myCtrl', function($scope, myService) { $scope.r = myService.myFunc(255); myService.getData().then(function(data){ console.log(data);//正确时走这儿 },function(data){ alert(data)//错误时走这儿 }); });</script>
Only provider is a service that can pass the .config() function. If you want to perform module-wide configuration before the service object is enabled, you should choose provider. It should be noted that when injecting the provider in the config function, the name should be: providerName Provider.
The advantage of using Provider is that you can use the Provider object in the app.config function before passing it to other parts of the application. to modify.
When you create a service using a Provider, the only properties and methods that can be accessed in your controller are the content returned by the $get() function.
<body><p ng-app="myApp" ng-controller="myCtrl"></p><script> var app = angular.module('myApp', []); //需要注意的是:在注入provider时,名字应该是:providerName+Provider app.config(function(myProviderProvider){ myProviderProvider.setName("大圣"); }); app.provider('myProvider', function() { var name=""; var test={"a":1,"b":2}; //注意的是,setter方法必须是(set+变量首字母大写)格式 this.setName = function(newName){ name = newName } this.$get =function($http,$q){ return { getData : function(){ var d = $q.defer(); $http.get("url")//读取数据的函数。 .success(function(response) { d.resolve(response); }) .error(function(){ d.reject("error"); }); return d.promise; }, "lastName":name, "test":test } } }); app.controller('myCtrl', function($scope,myProvider) { alert(myProvider.lastName); alert(myProvider.test.a) myProvider.getData().then(function(data){ //alert(data) },function(data){ //alert(data) }); });</script></body>
<body><p ng-app="myApp"> 在过滤器中使用服务: <h1>{{255 | myFormat}}</h1></p><script> var app = angular.module('myApp', []); app.service('hexafy', function() { this.myFunc = function (x) { return x.toString(16); } }); app.filter('myFormat',['hexafy', function(hexafy) { return function(x) { return hexafy.myFunc(x); }; }]);</script></body>
This article ends here (if you want to see more, just Go to the PHP Chinese website AngularJS User Manual to learn). If you have any questions, you can leave a message below.
The above is the detailed content of Detailed explanation of custom services in AngularJS, introduction to the usage of factory, service and provider. For more information, please follow other related articles on the PHP Chinese website!