angular服务
看一张图说明provider,服务等关系:
除了Constant之外,所有这些类型的服务,背后都是通过Provider实现的。最明显的一个证明就是,当你使用未定义的服务时,angular给你的错误提示是它对应的Provider未找到。比如说使用了一个未定义的服务test,那么错误提示是: Unknown provider:testProvider<- test。
provider必须有一个$get方法,声明方式如下:
angular.module('myApp').provider('greeting', function(){
var name ='world';
this.setName = function(name){
name = name;
};
this.$get = function(){
return 'hello, ' + name;
}
})
使用时:
angular.module('myApp').controller('someCtrl', function($scope, greeting){
$scope.message = greeting;
}))
对这个Provider进行配置:
angular.module('myApp').config(function(greetingProvider){
greetingProvider.setName('lyy');
})
注意,配置时要在名称后加provider并遵循驼峰命名法,这样angular才能正确注入该Provier。
Service很适合在Controller中通信或共享数据,Service里可以不用返回任何东西,因为angular会调用new关键字来创建对象。
angular.module('myApp').service('greeting', function(){
this.sayHello = function(name){
return 'hello, ' + name;
}
})
使用:
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;
})
})