angular服务app
服务是对公共代码的抽象,因为依赖注入的要求,服务都是单例的,这样咱们才能处处注入它们,而不用去管理它们的生命周期。
angular的服务有如下几种类型:
常量(Constant): 用于声明不会被修改的值。
变量(Value): 用于声明会被修改的值。
服务(Service): 这个名称跟服务这个大概念同名,就种行为就像是给本身孩子取名为"孩子"。只须要建立这个服务,而后等angular把它new出来,保存这个服务,而后就能够处处注入了。
工厂(Factory): 它跟上面的Service不同,它不会被new出来。angular会调用这个函数,得到返回值,而后保存这个返回值,供它处处调用。
供应商(Provider): 在整个服务启动以前,进行一些模块化的配置。
看一张图说明provider,服务等关系:ide
除了Constant以外,全部这些类型的服务,背后都是经过Provider实现的。最明显的一个证实就是,当你使用未定义的服务时,angular给你的错误提示是它对应的Provider未找到。好比说使用了一个未定义的服务test,那么错误提示是: Unknown provider:testProvider<- test。模块化
Provider
provider必须有一个$get方法,声明方式以下:函数
angular.module('myApp').provider('greeting', function(){ var name ='world'; this.setName = function(name){ name = name; }; this.$get = function(){ return 'hello, ' + name; } })
使用时:ui
angular.module('myApp').controller('someCtrl', function($scope, greeting){ $scope.message = greeting; }))
对这个Provider进行配置:this
angular.module('myApp').config(function(greetingProvider){ greetingProvider.setName('lyy'); })
注意,配置时要在名称后加provider并遵循驼峰命名法,这样angular才能正确注入该Provier。spa
Service
Service很适合在Controller中通讯或共享数据,Service里能够不用返回任何东西,由于angular会调用new关键字来建立对象。日志
angular.module('myApp').service('greeting', function(){ this.sayHello = function(name){ return 'hello, ' + name; } })
使用:code
angular.module('myApp').controller('someCtrl', function($scope, greeting){ $scope.message = greeting.sayHello('world'); }))
至关于:对象
angular.module('myApp').provider('greeting', function(){ this.$get = function(){ var greeting = function(){ this.sayHello = function(name){ return 'hello, ' + name; } } return new greeting(); } })
Factory
Factory和Service的区别就是:factory是普通function,而service是一个构造器,因此factory能够返回任何东西,而service能够不返回。
angular.module('myApp').factory('greeting', function(){ return 'hello, world'; })
Constant
Constant比较特殊,它不是Provider的语法糖,并且它的初始化时机很是早,能够在angular.module('myApp').config()中注入,而其余的服务除了Provider以外都不能够。这就意味着,若是你要在config中使用一个全局配置项,那么它就只能声明为常量。Constant不能被装饰器(decorator)装饰。
angular.module('myApp').constant('name','lyy');
注入到config中:
angular.module('myApp').config(function(name){ $scope.userName=name; })
Value
Value与Constant的区别是,Value能够被修改,不能注入到config中,可是能被装饰器(decorator)装饰。
angular.module('myApp').value('name','lyy');
angular提供了那么多服务,那么咱们应该何时用适合的服务呢?
若是是纯数据,选Value;
若是还须要添加行为,改写成Service;
发现须要经过计算给出结果,改写成Factory;
须要进行全局配置,改写成Provider。
Decorator
Decorator比较特殊,它不是provider,它是用来装饰其余provider的。可是对于Decorator必定要慎用。
好比说有一个第三方库叫ui,它有一个prompt函数,咱们不能改它的源码,可是须要让它每次弹出提问框时都在控制台输出一条记录,那么咱们能够这样写:
angular.module('myApp').config(function($provide){ //$delegate是ui的原始服务 $provide.decorator('ui', function($delegate){ //保存原始的prompt函数 var originalPrompt=$delegate.prompt; //用本身的prompt代替 $delegate.prompt=function(){ //先执行原始的prompt函数 originalPrompt.apply($delegate, arguments); //写一条日志 console.log('prompt'); }; //返回原始服务的实例 return $delegate; }) })