0

I have an object reportsService, which for each call it make's, it initialises a new object called serviceCall. Each method needs to instantiate it's own instance of serviceCall.

Is using $injector.get() the correct way to do this?

app.factory('reportsService', ['$injector', function ($injector) {
    var o = {};
    o.getServiceCall = function () {
        return $injector.get('serviceCall');
    };
    o.getOriginCompositionData = function (ajaxOptions) {
        ajaxOptions.url = '/test/SpiderRequestOriginComposition';
        o.getServiceCall().initialize(ajaxOptions);
    };
    o.getExeuctionTimeData = function (ajaxOptions) {
        ajaxOptions.url = '/test/SpiderRequestExeuctionTime';
        o.getServiceCall().initialize(ajaxOptions);
    };
    o.getCacheCompositionData = function (ajaxOptions) {
        ajaxOptions.url = '/test/SpiderRequestCacheComposition';
        o.getServiceCall().initialize(ajaxOptions);
    };
    return o;
}]);

1 Answer 1

2

You could simply inject a second parameter called "serviceCall" after (or I guess instead of) "$injector" and use that. It'll be captured in closure and useable from any of your "o" function.

Sign up to request clarification or add additional context in comments.

5 Comments

I wanted to do this, but if I include it as a parameter in my factory declaration, I only get one instance of it right? Because I need a different instance for each method...
Even with $injector.get, it's the same instance. In Angular (unlike Guice for example that has different "scopes") anything injected is a singleton.
It's actually kind of confusing in my opinion -- whether you use a factor or service, it's only ever instantiated once. Makes me wonder why "factory" even exists.
Thanks for the help, what I don't get now, is how you create an object which isn't a singleton, but still doesn't pollute the global namespace lol
Have created a new question for this, refer: stackoverflow.com/questions/20321915/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.