what's the difference between factory and service?
This question already has an answer here:
As we all know, we can define a service like this:
app.service('MyService', function () {
this.sayHello = function () {
console.log('hello');
};
});
.service()
is a method on our module that takes a name and a function that defines the service. Pretty straight forward. Once defined, we can inject and use that particular service in other components, like controllers, directives and filters, like this:
app.controller('AppController', function (MyService) {
MyService.sayHello(); // logs 'hello'
});
Now the same thing as a factory:
app.factory('MyService', function () {
return {
sayHello: function () {
console.log('hello');
};
}
});
Again, .factory()
is a method on our module and it also takes a name and a function, that defines the factory. We can inject and use that thing exactly the same way we did with the service.
We can see that a service is a constructor function whereas a factory is not . Somewhere deep inside of this Angular world, there's this code that calls Object.create()
with the service constructor function, when it gets instantiated. However, a factory function is really just a function that gets called, which is why we have to return an object explicitly.
no matter what we use, service()
or factory()
, it's always a factory that is called which creates a provider for our service.
Basically the difference between the service and factory is as follows:
app.service('myService', function() {
// service is just a constructor function
// that will be called with 'new'
this.sayHello = function(name) {
return "Hi " + name + "!";
};
});
app.factory('myFactory', function() {
// factory returns an object
// you can run some code before
return {
sayHello : function(name) {
return "Hi " + name + "!";
}
}
});
Both of them are all Singletons
Also keep in mind that in both cases, angular is helping you manage a singleton. Regardless of where or how many times you inject your service or function, you will get the same reference to the same object or function.
Source: service vs factory
链接地址: http://www.djcxy.com/p/77886.html上一篇: 控制器是否应该拨打服务或工厂?
下一篇: 工厂和服务有什么区别?