Angular 提供了3种方法来创建并注册我们自己的 service。
Factory
Service
Provider
1.Factory
创建一个对象,为它添加属性,然后把这个对象返回出来。
2.Service
用"new"关键字实例化的。因此,你应该给"this"添加属性,然后 service 返回"this"。
3.Provider
是唯一一种可以传进 .config() 函数的 service。
angularJS——自定义服务provider之$get
可以认为provider有三个部分:
第一部分是私有变量和私有函数,这些变量和函数会在以后被修改。
第二部分是在app.config函数里可以访问的变量和函数,所以,他们可以在其他地方使用之前被修改。注意,这些变量和函数一定要添加到this上面才行。
第三部分是在控制器里可以访问的变量和函数,通过$get函数返回。
当使用 provider创建服务的时候,唯一可以让控制器访问的属性和方法是在$get()函数里返回的属性和方法。
使用Provider的优点就是,你可以在Provider对象传递到应用程序的其他部分之前在app.config函数中对其进行修改。
当你使用Provider创建一个service时,唯一的可以在你的控制器中访问的属性和方法是通过$get()函数返回内容。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0">
<title>angular gtest</title>
<script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
<script type="text/javascript">
var ap = angular.module("HelloApp",[])
ap.controller("firstController",function ($scope,myFactory) {
//用 Factory 就是创建一个对象,为它添加属性,然后把这个对象返回出来。
//你把 service 传进 controller 之后,在 controller 里这个对象里的属性就可以通过 factory 使用了
$scope.astFactory = myFactory.getAtr();
console.log("factory ast=",$scope.astFactory);
});
ap.controller("secondController",function ($scope,myService) {
//Service 是用"new"关键字实例化的。因此,你应该给"this"添加属性,
//然后 service 返回"this"。你把 service 传进 controller 之后,在controller里 "this" 上的属性就可以通过 service 来使用了。
$scope.astService = myService.getAtrl();
console.log("service ast=",$scope.astService);
});
ap.controller("thirdController",function($scope,myProvider){
//获取provider中$get返回的值
$scope.astProvider = myProvider.getAtr3();
console.log("provider ast=",$scope.astProvider);
$scope.data = myProvider.thingOneConfig;
console.log("data.thingOneConfig===",$scope.data);
});
//myFactory
ap.factory("myFactory",function(){
var atr="";
var service = {};
service.getAtr =function(){
return atr;
}
return service;
});
//myService
ap.service("myService",function(){
var atr="service";
//通过this进行属性的添加
this.getAtrl =function(){
return atr;
}
});
//myProvider
ap.provider('myProvider',function() {
this.atr3="111";
this.thingFromConfig="222";
this.$get =function(){
var that =this;
//$get函数返回对象属性,可以在controller中进行访问
return {
getAtr3:function(){
return that.atr3;
},
'thingOneConfig':that.thingFromConfig
}
}
});
//config函数里可以访问的变量和函数,所以,他们可以在其他地方使用之前被修改。注意,这些变量和函数一定要添加到this上面才行。
ap.config(function(myProviderProvider){
console.log("config....");
myProviderProvider.thingFromConfig ="this was set in config()";
});
</script>
</head>
<body ng-app="HelloApp">
<div ng-controller="firstController">
<p>使用factory获取到的结果:{{astFactory}}</p>
</div>
<div ng-controller="secondController">
<p>使用service获取到的结果:{{astService}}</p>
</div>
<div ng-controller="thirdController">
<p>使用providers获取到的结果:{{astProvider}}</p>
</div>
</body>
</html>
网友评论