2

我试图了解服务和工厂之间的本质区别是什么(在 AngularJS 中)。每次调用时都说工厂是单例,服务是新对象,这是真的吗?

4

2 回答 2

1

在 javascript 中,函数可以类似于具有实例变量、实例方法的类,并且可以新建:

// creating a class Box
function Box(col)
{
   // instance member variable color, default to 'Red' if no color passed
   var color = col || 'Red';

   // instance method
   this.getColor = function()
   {
      return color;
   }
}

要实例化一个 Box,并用不同的颜色对其进行初始化:

var blueBox = new Box("blue");
alert(blueBox.getColor()); // will alert blue

var greenBox = new Box("green");
alert(greenBox.getColor()); // will alert green

Angular 服务用于注册构造函数,如 Box 示例。当服务被注入时,服务的一个实例被传递到你的函数中:

// declare a service
app.service('box', Box);

// inject instance of Box into controller: 'box' is a new Box()
app.controller('ctrl', function(box) {
    alert(box.getColor()); // alerts  'Red'
});

相反,角度工厂不返回函数的实例。相反,它缓存并返回调用函数的结果:

// declare a factory
app.factory('user', function() {

    // return an object literal
    return  {
        name: 'john',
    }
});


app.controller('ctrl', function(user) {
   alert(user.name);// user is the object literal which was returned from the user factory.
};

将工厂视为返回函数结果的一种方式;结果是所有注入之间共享的单例。

将服务视为实例化类(或函数构造函数)的一种方式;该实例也是一个单例,并在所有注入之间共享。

工厂和服务都是单例的。

于 2014-06-02T08:05:01.337 回答
1

服务和工厂之间的唯一区别是服务是用 new 调用的

stuffToInject = new Service();

而工厂只是像函数一样被调用

stuffToInject = Factory();

否则是一样的,工厂和服务都是单例的。您需要问自己的唯一问题是我的服务是否需要新的操作员。如果不需要,请使用module.factory,else module.service

例子:

function(){
  this.foo=function(){
  }
}

需要注册到 module.service

function(){
   return {
    foo:function(){}
   };
}

可以注册到 module.factory

于 2014-06-02T08:51:47.967 回答