Using a factory inside another factory AngularJS

廉价感情. 提交于 2019-12-09 08:30:38

问题


I have a module...

angular.module('myModule', []);

And then a factory

angular.module('myModule')
.factory('factory1', [
  function() {
    //some var's and functions
}
]);

And then another factory

angular.module('myModule')
.factory('factory2', [
  function() {
    //some var's and functions BUT I want to use some var's from factory1
}
]);

But I want to use some variables from factory1 inside factory2, how can I inject factory1 into factory2?


回答1:


This is what I would do:

On Factory One

angular.module('sampleApp')
    .factory('factory1', function() {
        var factory1 = {};

        factory1.method1 = function () {
            return true;
        };

        factory1.method2 = function () {
            return "hello";
        };

        return factory1;
    }
);

On Factory Two

angular.module('sampleApp')
    .factory('factory2', ['factory1',
        function(factory1) {

            var factory2 = {};

            factory2.method3 = function () {
                return "bye vs " + factory1.method2();
            };

            return factory2;
        }
    ]);



回答2:


This is what i did and worked fine. Call SessionPresenters from Session

angular.module('tryme3App')
    .factory('Session', function ($resource, DateUtils, SessionPresenters) {
        return $resource('api/sessions/:id', {}, {
            'query': { method: 'GET', isArray: true},
            'get': {
                method: 'GET',
                transformResponse: function (data) {
                    data = angular.fromJson(data);

                    var result = SessionPresenters.get({id: data.id})
                    data.presenters = result; 
                    return data;
                }
            },
            'update': { method:'PUT' }
        });
    }).factory('SessionPresenters', function ($resource, DateUtils) {
        return $resource('api/session.Presenters/:id', {}, {
            'query': { method: 'GET', isArray: true},
            'get': {
                method: 'GET', isArray: true
            },
            'update': { method:'PUT' }
        });
    });


来源:https://stackoverflow.com/questions/23115620/using-a-factory-inside-another-factory-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!