18

我是 AngularJS 新手,我刚刚开始了解factory,servicecontroller. 据我了解, afactory用于返回可以注入的“值对象”。我见过的大多数例子都是这样的:

angular.module('module.factories', function() {
    factory('FactoryObject', function() {
        return {
            someFunction: function(someParam) {};
            someOtherFunction: function(someOtherParam) {});
        };
    });
});

在我的controller中,我希望能够使用这个对象,但我想在控制器中初始化/实例化它,因为它可以根据控制器中的事件/动作重新初始化。因此,我想知道是否可以在工厂中返回构造函数?

angular.module('module.factories', function() {
    factory('FactoryObject', function() {

        function FactoryObject(initParam) {
        }

        FactoryObject.prototype.someFunction = function() {};

        return FactoryObject;

    });
});

这是一个适合角度工厂的模式吗?还是将工厂用于这样的自定义对象只是“矫枉过正”?我应该将它包含在库 js 文件中并从那里引用它吗?将它放在工厂的一个好处是它很容易在测试中模拟它,因为它会被注入到使用它的地方。Angular 中是否有其他机制可以替代使用?

4

4 回答 4

8

我有同样的问题。这是我实现的:

angular.module('foo', [])
.factory('Foo', ['$http', function($http) {
  return function(a, b) {
    this.arr = [];
    this.a = a;
    this.b = b;
    this.random = Math.floor(Math.random()*11);

    this.someFunc = function(c) {
      this.arr.push(c);
    };
  };
}]);

现在,我可以这样做:

var f1 = new Foo('A', 'B');
f1.random;  // i.e. 0
f1.someFunc('z');  // only affects f1.arr
var f2 = new Foo('C', 'D');
f2.random;  // i.e. 8
f2.someFunc('y');  // only affects f2.arr

使事情更加模块化。希望有帮助。

于 2013-06-14T00:07:41.093 回答
3

你说得对,这是创建可注入“类”(构造函数)的方法。但是,factory只有当您需要注入其他内容以供您的班级使用时,才需要使用:

.factory('Class', ['$q', function ($q) {
    function Class () {}
    Class.prototype = {
        constructor: Class,
        doSomeAsyncAction: function () {
            return $q(function (resolve, reject) {
                // ...
            });
        },
        // ...
    };
    return Class;
})

如果您正在创建一个完全独立的类(例如某些数据结构),您可以使用constant,以便您的类即使在服务提供者中也可用:

(function (undefined) {
    function Class () {}
    Class.prototype = { ... };
    angular.module(...)
        .constant('Class', Class);
})();

作为旁注,使用provider不会帮助你。提供者服务于完全不同的目的,并且(除其他外)返回一个工厂函数,然后在第一次请求注入时_once_使用该函数来创建服务的单个实例。提供程序用于让您在应用程序构建的 _config 阶段_ 配置单个服务实例(请参阅文档)。

于 2014-12-18T06:19:39.603 回答
1

I had the same question. I found a terrific article on how to setup Object-oriented AngularJS Services. Here's the article. Pay attention to the note about using Factories and not Services. It also covers extending your objects. I found it super easy to setup and it fit perfectly with Angular while keeping the Javascript simple and straight forward.

For Factory services which are singletons and do not need to be instantiated I use the object literal approach which has some performance advantages.

于 2014-12-18T06:05:54.753 回答
1

这是我解决问题的方法:

(function (myModule) {
    'use strict';

    myModule.service('myService', [
        function() {
            var serivce = this;
            var obj = null;

            service.func1 = function(a, b) {

            }

            service.func2 = function(c, d) {
                . . .
                return something;
            }

            var constructor = function(myObj) {
                obj = myObj;

                return service;
            }

            return constructor;
        }
    ]);
}(angular.module("myModule")))

(function(myModule) {
    'use strict';

    myModule.controller('myController', [
        '$scope', 'myService', function($scope, myService) {

            var service = myService($scope.someObj);

            $scope.someOtherObj = service.func2($scope.a, $scope.b);

        }
    ]);
}(angular.module("myModule")))

服务返回的唯一内容是构造函数,然后服务返回服务的其余部分。

于 2016-02-22T18:33:55.723 回答