angularjs 中 Factory,Service,Provider 之间的区别

本片文章是使用了 angularjs 中使用 service 在controller 之间 share 对象和数据 的code(http://jsfiddle.net/kn46u0uj/1/) 来进行演示 Factory,Service,Provider 之间的区别

1. Factory

factory('dataService',function(){
    return {
        golbal_sitename:"this is the shared value",
        sayHello:function(msg){
            alert(msg);
        }
    }
})

注意看上面的代码,我们定义dataService 里面 ,后面的funciton 直接返回的是一个对象。 反回对象里面可以定义属性和方法,上面就是返回了一个golbal_sitename属性和sayHello方法。

简单点说就是: 在factory 定义的function 返回的对象上面定义些属性和方法, 等注入到controller后,就可以在controller调用这些属性和方法了。

2. 我们来用service改写上面的代码

service('dataService',function(){
    this.golbal_sitename = "this is the shared value";
    this.sayHello = function(msg){
            alert(msg);
    };
});

注意上面的代码和factory 定义的区别,这里我们去掉了return 添加了this关键字。换句话说 factory 定义里面的function 其实是返回个对象,而service 定义里面的funciton 返回的是个类定义。

也就是说service 里面定义的dataService 最后是通过new 后面定义的function 来实例化的。

http://jsfiddle.net/kn46u0uj/3/

3. 使用Provider再次改写代码

Provider 定义的 service 可以传进 .config() 函数。当我们需要在service 启用前配置其模块参数时,就需要使用Provider来定义service.

代码如下:

provider('dataService',function(){
    this.$get = function(){
        return {
            golbal_sitename:"this is the shared value",
            sayHello:function(msg){
                    alert(msg);
            }
        }
  };
})

http://jsfiddle.net/kn46u0uj/5/

上面使用三种方式定义的service 都可以正常工作, 唯一需要注意的就是使用当service 需要传入到config中进行配置的时候,一定要使用provider进行定义。

原文地址:https://www.cnblogs.com/slardar1978/p/4203979.html