gpt4 book ai didi

angularjs - 创建服务方法时 module.service 和 module.factory 有什么区别

转载 作者:行者123 更新时间:2023-12-03 06:28:29 31 4
gpt4 key购买 nike

我不知道什么是最佳实践以及我应该使用什么。

下面两种方法有什么区别?

module.service(..);

module.factory(..);

最佳答案

Pawel Kozlowski 发布了一篇有关此内容的精彩 Google 群组帖子:

https://groups.google.com/forum/#!msg/angular/hVrkvaHGOfc/idEaEctreMYJ

引自鲍威尔:

in fact $provide.provider, $provide.factory and $provide.service are more or less the same thing in the sense that all of them are blueprints / instructions for creating object instances (those instances are then ready to be injected into collaborators).

$provide.provider is the most spohisticated method of registering blueprints, it allows you to have a complex creation function and configuration options.

$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 is for cases where the whole creation logic boils down to invoking a constructor function.

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.

这里是演示的附带 fiddle (来自线程):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()];
}

关于angularjs - 创建服务方法时 module.service 和 module.factory 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16565105/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com