provider->factory->servicehtml
都能提供service,可是又有差异angularjs
service
第一次被注入时实例化,只实例化一次,整个应用的生命周期中是个单例模式,能够用来在controller之间传递数据api
//使用new关键字实例化,因此直接使用this定义service //不知道为啥就看看js中的this怎么玩的 .service('myService', ['', function() { this.getName = function() { return 'CooMark'; } }])
factoryapp
//返回一个对象,可能这是你喜欢的方式,使用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在你开始注入以前就已经实例化,开发共享的模块的时候经常使用它,可以在使用以前进行配置,好比你可能须要配置你的服务端的urlide
//两种形式的参数,都是为了获得一个带有$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/295067this