Why use a service?

I have been using AngularJS on a new project and I really like it. So much so I think I will do all my future web projects with it. I have done lots of reading on the different types of Provider there are in Angular and have used Factories and Values a lot.

I understand the difference between Services and Factories in as far as a Service is an instance of the function you pass to module.service() and a Factory is the return value of the function you pass to module.factory() (often an object literal in my case). I can not really see why you would need to use a Service though.

The functionality of a Service seems identical to returning an object literal with properties and methods from the factory function. For example:

module.service('MyService', function () {
    this.value = 'Hello';

    this.sayValue = function () {
        alert(this.value);
    };
});

module.factory('MyFactory', function () {
    // Can also do some things before return statement
    return {
        value: 'Hello',
        sayValue: function () {
            alert(this.value);
        }
    };
});

The factory has the added functionality of being able to perform some actions before the return statement is encountered.

Can anyone explain where they draw the line between Service and Factory usage?

Thanks in advance


As shown in the docs at https://docs.angularjs.org/guide/providers#service-recipe , if you want to do the following:

myApp.factory('unicornLauncher', ["apiToken", function(apiToken) {
  return new UnicornLauncher(apiToken);
}]);

Then you can just do:

myApp.service('unicornLauncher', ["apiToken", UnicornLauncher]);

The docs say this is

Much simpler!

But I have to say, in my opinion, I don't think it's clear, and the saving of a line of code isn't worth it in this case. For both clarity and flexibility, I now always use a factory.

链接地址: http://www.djcxy.com/p/77546.html

上一篇: 无法从角度检索喷油器

下一篇: 为什么要使用服务?