angularjs中provider,factory,service的区别和用法
2016-10-25 09:09
411 查看
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'; } } } }); }])
参考:
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
相关文章推荐
- [置顶] 跟我学AngularJs:Service、Factory、Provider依赖注入使用与区别
- AngularJs:Service、Factory、Provider依赖注入使用与区别
- AngularJS的Provider, Value, Constant, Service, Factory, Decorator的区别与详解
- AngularJS中service,factory,provider的区别(转载:http://my.oschina.net/tanweijie/blog/295067)
- AngularJS的Provider, Value, Constant, Service, Factory, Decorator的区别与详解
- AngularJS中service,factory,provider的区别
- angularJs中service的三种方法以及区别(factory,service,provider三者的区别)
- AngularJS中service,factory,provider的区别
- angularJs中service的三种方法以及区别(factory,service,provider三者的区别)
- AngularJs:Service、Factory、Provider依赖注入使用与区别
- AngularJS之Provider, Value, Constant, Service, Factory, Decorator的区别与详解
- AngularJS中service,factory,provider的区别
- AngularJS中service,factory,provider的区别
- angularjs中service、factory和provider的区别
- AngularJS的自定义服务,factory、provider、service、constant、value等方法的区别
- AngularJS中service,factory,provider的区别
- angularjs中provider、factory和service三者的写法与区别
- angularjs 中 Factory,Service,Provider 之间的区别
- AngularJS 中的 factory、 service 和 provider区别
- angularjs中service,factory,provider的区别