angularjs中provider,factory,service的区别和用法

时间:2021-07-13 01:21:25

angularjs中provider,factory,service的区别和用法

provider->factory->service

都能提供service,但是又有差别

service

第一次被注入时实例化,只实例化一次,整个应用的生命周期中是个单例模式,可以用来在controller之间传递数据

//使用new关键字实例化,所以直接使用this定义service
//不知道为啥就看看js中的this怎么玩的
.service('myService', ['', function() {
this.getName = function() {
return 'CooMark';
}
}])

factory

//返回一个对象,可能这是你喜欢的方式,使用call的方式实例化,其他的和service一样
//Internally this is a short hand for $provide.provider(name, {$get: $getFn}).
angular.module('app', [])
.factory('myFactory', ['', function() {
return {
getName: function() {
return 'CooMark';
},
getTitle: function() {
return 'Engineer'
}
}
}])

provider

这是唯一能注入到config的service,这样定义的service在你开始注入之前就已经实例化,开发共享的模块的时候常常使用它,能够在使用之前进行配置,比如你可能需要配置你的服务端的url

//两种形式的参数,都是为了得到一个带有$get属性的对象
// Object: then it should have a $get method. The $get method will be invoked using $injector.invoke() when an instance needs to be created.
// Constructor: a new instance of the provider will be created using $injector.instantiate(), then treated as object.
angular.module('app', [])
.config(['$provider', function() {
$provider.provider('myProvider', function() {
this.$get = function() {
return {
getName: function() {
return 'CooMark';
}
}
}
});
$provider.provider('myProvider', {
$get: function() {
return {
getName: function() {
return 'CooMark';
}
}
}
});
}])

angularjs中provider,factory,service的区别和用法

参考:

https://docs.angularjs.org/api/auto/service/$provide

http://www.cnblogs.com/joyco773/p/5702337.html

http://www.360doc.com/content/16/0728/14/22900036_579091190.shtml

https://my.oschina.net/tanweijie/blog/295067