感到困惑的服务VS厂 [英] Confused about Service vs Factory

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

问题描述

据我了解,当一个工厂里面我返回被注入控制器的对象。当一个服务中,我与对象使用这个并没有返回任何处理。

As I understand it, when inside a factory I return an object that gets injected into a controller. When inside a service I am dealing with the object using this and not returning anything.

我的假设下,一个服务是的一直单身的,而一个新工厂对象在每个控制器被注入。然而,事实证明,工厂对象是单身吗?

I was under the assumption that a service was always a singleton, and that a new factory object gets injected in every controller. However, as it turns out, a factory object is a singleton too?

举例code证明:

var factories = angular.module('app.factories', []);
var app = angular.module('app',  ['ngResource', 'app.factories']);

factories.factory('User', function () {
  return {
    first: 'John',
    last: 'Doe'
  };
});

app.controller('ACtrl', function($scope, User) {
  $scope.user = User;
});

app.controller('BCtrl', function($scope, User) {
  $scope.user = User;
});

在不断变化的 user.first ACtrl 事实证明, user.first BCtrl 也发生了变化,如: 用户是一个单?

When changing user.first in ACtrl it turns out that user.first in BCtrl is also changed, e.g. User is a singleton?

我的假设是,一个新的实例是在一个控制器注射了工厂?

My assumption was that a new instance was injected in a controller with a factory?

推荐答案

所有角度的服务宗旨是单身

文件(见的服务为单身的): https://docs.angularjs.org/guide/服务

最后,要认识到所有的角度服务是应用程序的单身是非常重要的。这意味着,只有一个每注射器的给定服务的实例。

Lastly, it is important to realize that all Angular services are application singletons. This means that there is only one instance of a given service per injector.

基本上服务和工厂之间的差如下:

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 + "!";
    }
  }
});

看看这个presentation约$提供: http://slides.wesalvaro.com/20121113/#/

这些切片在AngularJs聚会之一使用:<一href=\"http://blog.angularjs.org/2012/11/more-angularjs-meetup-videos.html\">http://blog.angularjs.org/2012/11/more-angularjs-meetup-videos.html

Those slides were used in one of the AngularJs meetups: http://blog.angularjs.org/2012/11/more-angularjs-meetup-videos.html

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

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