0

Now i wish to create an object that you can instanciate at any time but that can still use angular services:

Take for instance the following object:

var myObject = function (variableOne, variableTwo) {
    this.variableOne = variableOne;
    this.variableTwo = variableTwo
};

myObject.prototype.useAngularService = function () {
    return $sessionStorage.user;   
};

Ofcourse this object cannot use $sessionStorage but my question is how would you create an object like that, that actually could utilize angular services?

The reason why i want to use this method instead of a service or a factory is basicly that i want different instances of this object and i am not looking for a singleton solution.

2 Answers 2

2

You could return your type from a factory. The factory would then have the Angular services and you would close around them.

yourModule.factory('yourName', function($sessionStorage) {
    var myObject = function (variableOne, variableTwo) {
        this.variableOne = variableOne;
        this.variableTwo = variableTwo
    };

    myObject.prototype.useAngularService = function () {
        return $sessionStorage.user;   
    };

    return myObject;
});

You can also request any registered service with $injector.get(...) but that makes for brittle code.

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

Comments

1

You would inject $sessionStorage as a dependency into your object upon construction:

var myObject = function ($sessionStorage, variableOne, variableTwo) {
    this.$sessionStorage = $sessionStorage;
    this.variableOne = variableOne;
    this.variableTwo = variableTwo
};

myObject.prototype.useAngularService = function () {
    return this.$sessionStorage.user;   
};

You would then create a service which acts as a factory for such objects:

function myObjectFactory($sessionStorage) {
    this.$sessionStorage = $sessionStorage;
}

myObjectFactory.prototype.getInstance = function (variableOne, variableTwo) {
    return new myObject(this.$sessionStorage, variableOne, variableTwo);
};

myModule.service('myObjectFactory', myObjectFactory);

You then include that factory as a dependency for your controller or other service:

myModule.controller('myController', function (myObjectFactory) {
    var obj = myObjectFactory.getInstance(1, 2);
    obj.useAngularService();
}

Comments

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.