问题描述
我不知道什么是最佳实践以及我应该使用什么.
I don't know what is the best practice and what I should use.
以下两种方法有什么区别?
What is the difference between below two methods?
module.service(..);
和
module.factory(..);
推荐答案
Pawel Kozlowski 在 Google 小组中发布了一篇很棒的帖子:
There is a great google group post about this from Pawel Kozlowski:
https://groups.google.com/forum/#!msg/angular/hVrkvaHGOfc/idEaEctreMYJ
引自鲍威尔:
实际上 $provide.provider, $provide.factory 和 $provide.service 是从某种意义上说,它们或多或少是相同的创建对象实例的蓝图/说明(那些然后准备好将实例注入到协作者中).
$provide.provider 是最复杂的注册方法蓝图,它可以让你有一个复杂的创建功能和配置选项.
$provide.provider is the most spohisticated method of registering blueprints, it allows you to have a complex creation function and configuration options.
$provide.factory 是 $provide.provider 的简化版本不需要支持配置选项但仍然想要一个更复杂的创建逻辑.
$provide.factory is a simplified version of $provide.provider when you don't need to support configuration options but still want to have a more sophisticated creation logic.
$provide.service 用于整个创建逻辑沸腾的情况归结为调用构造函数.
$provide.service is for cases where the whole creation logic boils down to invoking a constructor function.
因此,根据您的构造逻辑的复杂性,您将选择 $provide.provider、$provide.factory 和 $provide.service 之一但最终你会得到一个新的实例.
So, depending on the complexity of your construction logic you would choose one of $provide.provider, $provide.factory and $provide.service but in the end what you are going to get is a new instance.
这是随附的小提琴演示(来自线程):http://jsfiddle.net/pkozlowski_opensource/PxdSP/14/
Here is the accompanying fiddle to demonstrate (from the thread): http://jsfiddle.net/pkozlowski_opensource/PxdSP/14/
和代码:
var myApp = angular.module('myApp', []);
//service style, probably the simplest one
myApp.service('helloWorldFromService', function() {
this.sayHello = function() {
return "Hello, World!"
};
});
//factory style, more involved but more sophisticated
myApp.factory('helloWorldFromFactory', function() {
return {
sayHello: function() {
return "Hello, World!"
}
};
});
//provider style, full blown, configurable version
myApp.provider('helloWorld', function() {
this.name = 'Default';
this.$get = function() {
var name = this.name;
return {
sayHello: function() {
return "Hello, " + name + "!"
}
}
};
this.setName = function(name) {
this.name = name;
};
});
//hey, we can configure a provider!
myApp.config(function(helloWorldProvider){
helloWorldProvider.setName('World');
});
function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) {
$scope.hellos = [
helloWorld.sayHello(),
helloWorldFromFactory.sayHello(),
helloWorldFromService.sayHello()];
}
这篇关于创建服务方法时,module.service 和 module.factory 有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!