AngularJS:工厂和服务? [英] AngularJS : Factory and Service?

查看:31
本文介绍了AngularJS:工厂和服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑 2016 年 1 月:因为这仍然受到关注.自从问这个我已经完成了一些 AngularJS 项目,对于那些我主要使用 factory 的项目,构建了一个对象并在最后返回了该对象.然而,我在下面的陈述仍然是正确的.

我想我终于明白了两者之间的主要区别,我有一个代码示例来演示.我也认为这个问题与建议的重复不同.副本表示该服务不可实例化,但如果您按照我在下面演示的方式设置它,它实际上是.可以将服务设置为与工厂完全相同.我还将提供代码,显示工厂故障转移服务的位置,这似乎没有其他答案.

如果我像这样设置 VaderService(即作为服务):

var module = angular.module('MyApp.services', []);module.service('VaderService', function() {this.speak = 函数(名称){return '加入黑暗面' + 名字;}});

然后在我的控制器中我可以这样做:

module.controller('StarWarsController', function($scope, VaderService) {$scope.luke = VaderService.speak('luke');});

使用service,注入控制器的VaderService被实例化,所以我可以调用VaderService.speak,但是,如果我将VaderService改为module.factory,控制器中的代码将不再起作用,这是主要区别.使用工厂时,注入控制器的 VaderService 实例化,这就是为什么在设置工厂时需要返回对象的原因(请参阅问题中我的示例).

但是,您可以以与设置工厂完全相同的方式设置服务(即让它返回一个对象),并且该服务的行为与工厂完全相同

根据这些信息,我认为没有使用工厂而不是服务的理由,服务可以做工厂所能做的一切,甚至更多.

下面的原始问题.

<小时>

我知道这已经被问过很多次了,但我真的看不出工厂和服务之间有任何功能差异.我读过这个教程:

在下面的示例中,我定义了 MyServiceMyFactory.请注意在 .service 中我如何使用 this.methodname. 创建了服务方法.在 .factory 中我创建了一个工厂对象并分配了方法到它.

AngularJS .service

<小时>

module.service('MyService', function() {this.method1 = 函数(){//..method1 逻辑}this.method2 = function() {//..method2 逻辑}});

AngularJS .factory

<小时>

module.factory('MyFactory', function() {var 工厂 = {};factory.method1 = function() {//..method1 逻辑}factory.method2 = function() {//..method2 逻辑}返厂;});

<小时>

也看看这些美丽的东西

对服务与工厂的困惑

AngularJS 工厂、服务和提供者

Angular.js:服务 vs 提供者 vs 工厂?

EDIT Jan 2016: Since this still gets attention. Since asking this I've completed a few AngularJS projects, and for those I mostly used factory, built up an object and returned the object at the end. My statements below are still true, however.

EDIT : I think I finally understand the main difference between the two, and I have a code example to demonstrate. I also think this question is different to the proposed duplicate. The duplicate says that service is not instantiable, but if you set it up as I demonstrated below, it actually is. A service can be set up to be exactly the same as a factory. I will also provide code that shows where factory fails over service, which no other answer seems to do.

If I set up VaderService like so (ie as a service):

var module = angular.module('MyApp.services', []);

module.service('VaderService', function() {
    this.speak = function (name) {
        return 'Join the dark side ' + name;
    }
});

Then in my controller I can do this:

module.controller('StarWarsController', function($scope, VaderService) {
    $scope.luke = VaderService.speak('luke');   
});

With service, the VaderService injected in to the controller is instantiated, so I can just call VaderService.speak, however, if I change the VaderService to module.factory, the code in the controller will no longer work, and this is the main difference. With factory, the VaderService injected in to the controller is not instantiated, which is why you need to return an object when setting up a factory (see my example in the question).

However, you can set up a service in the exact same way as you can set up a factory (IE have it return an object) and the service behaves the exact same as a factory

Given this information, I see no reason to use factory over service, service can do everything factory can and more.

Original question below.


I know this has been asked loads of times, but I really cannot see any functional difference between factories and services. I had read this tutorial: http://blogs.clevertech.biz/startupblog/angularjs-factory-service-provider

And it seems to give a reasonably good explanation, however, I set up my app as follows:

index.html

<!DOCTYPE html>
<html>
    <head>
    <title>My App</title>
    <script src="lib/angular/angular.js"></script>
    <script type="text/javascript" src="js/controllers.js"></script>
    <script type="text/javascript" src="js/VaderService.js"></script>
    <script type="text/javascript" src="js/app.js"></script>
    </head>

    <body ng-app="MyApp"> 
        <table ng-controller="StarWarsController">
            <tbody>
            <tr><td>{{luke}}</td></tr>
            </tbody>
        </table>
    </body>
</html>

app.js:

angular.module('MyApp', [
  'MyApp.services',
  'MyApp.controllers'
]);

controllers.js:

var module = angular.module('MyApp.controllers', []);

module.controller('StarWarsController', function($scope, VaderService) {
    var luke = new VaderService('luke');
    $scope.luke = luke.speak();
});

VaderService.js

var module = angular.module('MyApp.services', []);

module.factory('VaderService', function() {
    var VaderClass = function(padawan) {
        this.name = padawan;
        this.speak = function () {
            return 'Join the dark side ' + this.name;
        }
    }

    return VaderClass;
});

Then when I load up index.html I see "Join the dark side luke", great. Exactly as expected. However if I change VaderService.js to this (note module.service instead of module.factory):

var module = angular.module('MyApp.services', []);

module.service('VaderService', function() {
    var VaderClass = function(padawan) {
        this.name = padawan;
        this.speak = function () {
            return 'Join the dark side ' + this.name;
        }
    }

    return VaderClass;
});

Then reload index.html (I made sure I emptied the cache and did a hard reload). It works exactly the same as it did with module.factory. So what is the real functional difference between the two??

解决方案

Service vs Factory


The difference between factory and service is just like the difference between a function and an object

Factory Provider

  • Gives us the function's return value ie. You just create an object, add properties to it, then return that same object.When you pass this service into your controller, those properties on the object will now be available in that controller through your factory. (Hypothetical Scenario)

  • Singleton and will only be created once

  • Reusable components

  • Factory are a great way for communicating between controllers like sharing data.

  • Can use other dependencies

  • Usually used when the service instance requires complex creation logic

  • Cannot be injected in .config() function.

  • Used for non configurable services

  • If you're using an object, you could use the factory provider.

  • Syntax: module.factory('factoryName', function);

Service Provider

  • Gives us the instance of a function (object)- You just instantiated with the ‘new’ keyword and you’ll add properties to ‘this’ and the service will return ‘this’.When you pass the service into your controller, those properties on ‘this’ will now be available on that controller through your service. (Hypothetical Scenario)

  • Singleton and will only be created once

  • Reusable components

  • Services are used for communication between controllers to share data

  • You can add properties and functions to a service object by using the this keyword

  • Dependencies are injected as constructor arguments

  • Used for simple creation logic

  • Cannot be injected in .config() function.

  • If you're using a class you could use the service provider

  • Syntax: module.service(‘serviceName’, function);

Sample Demo

In below example I have define MyService and MyFactory. Note how in .service I have created the service methods using this.methodname. In .factory I have created a factory object and assigned the methods to it.

AngularJS .service


module.service('MyService', function() {

    this.method1 = function() {
            //..method1 logic
        }

    this.method2 = function() {
            //..method2 logic
        }
});

AngularJS .factory


module.factory('MyFactory', function() {

    var factory = {}; 

    factory.method1 = function() {
            //..method1 logic
        }

    factory.method2 = function() {
            //..method2 logic
        }

    return factory;
});


Also Take a look at this beautiful stuffs

Confused about service vs factory

AngularJS Factory, Service and Provider

Angular.js: service vs provider vs factory?

这篇关于AngularJS:工厂和服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆