加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 在创建服务方法时,module.service和module.factory

发布时间:2020-12-17 08:29:25 所属栏目:安全 来源:网络整理
导读:我不知道什么是最佳实践和我应该使用。 下面两种方法有什么区别? module.service(..); 和 module.factory(..); 有一个伟大的谷歌集团帖子关于这一点从Pawel Kozlowski: https://groups.google.com/forum/#!msg/angular/hVrkvaHGOfc/idEaEctreMYJ 来自Powel
我不知道什么是最佳实践和我应该使用。

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

module.service(..);

module.factory(..);
有一个伟大的谷歌集团帖子关于这一点从Pawel Kozlowski:

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

来自Powel:

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.

这是附带的小提琴演示(从线程):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()];
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读