How can AngularJS factory return an object

All we need is an easy explanation of the problem, so here it is.

I have a requirement in which i should write factory. This factory should contain 3 function init, save and delete

I should call init function from controller. This function returns an object. This object has the function to execute the add and delete function.

how can i achieve this?

Following is my code, It execute the init function successfully but when i try to use the object which was returned in add or delete, it says object is empty

angularApp.factory('SomeFactory', function(){
var client = new Client(); // this client is defined in another javascript file
                           // this is the object which we should return
var clientReady = function () {
     var cv = client.GetVersion();
     showIDs();
};
return {
    initClient:function(requiredUID){
        client.setAttribute("clientReadyCallback",clientReady);
    }//,

};
 var add = function () {
     client.someapi;
 };
var delete = function () {
     client.someapi;
 };`
});

in controller i call the below calls
SomeFactory.initClient("username");
SomeFactory.add();// throws error

How can i achieve this?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

First of all, you aren’t returning a factory, but a service. It’s a factory that creates a service, so adjust your naming convention like so: app.factory('someService'

Your code is a mess and has errors, so I’ll just show you the basics of returning a service object.

app.factory('someService', function() {
  var someService = {  //build this object however you want
    add: function() {

    },
    save: function() {

    }
  };

  return someService; //return the object
}); //end factory

in your controller: someService.add();

Method 2

A factory and service are actually different in one simple but very, very important way.

A Factory returns services that can be new’d.

In other words, you can do this:

var instanceOne = new $factory;
var instanceTwo = new $factory;

…and then call them as separate entities. This is in fact what the factory pattern is all about.

Here is a simple example of a factory that you can get copies of…

app.factory('myFactory', function() {
    return {
        talk: function(what) {
            return "Say " + what;
        }
    }
});

If instead you want a Service, you need to reference methods inside it by this.methodName, then you’re just returning the service itself, or, a singleton pattern. Like so…

app.service('myService', function() {
    this.talk = function(what) {
        return "Say " + what;
    };
});

As a side note; if you look at my code, Angular now supports actually defining services via the service keyword, or, the factory keyword. In the source, you can see that they both literally reference the same code.

That’s how similar they are, and in fact these two factory and service methods are interchangeable, so, if you got confused at first, don’t sweat it; there is almost no difference at all… almost 🙂

… lots of people seem to want to know: “How can you return a factory or service that just has one function, i.e., it, itself, is the function?” Easy.. like this…

app.factory('myFactory', function() {
    return function(what) {
            return "Say " + what;
    }
});

Method 3

this is an Authentification factory from a real project

//factory using firebase Athentication service
myApp.factory('Authentication', function($firebase,$firebaseAuth,$location){

	var ref = new Firebase("URL_to_firebase");
    var simpleLogin = $firebaseAuth(ref);

    var myObject = {
    	//user is the data from the FORM
    	login : function(user){
    		return simpleLogin.$authWithPassword({
			  email: user.email,
			  password: user.password
			});
    	}//login
    }//password

    return myObject;//factory should return something

});

//and then you call like this in your controller
myApp.controller('myController' , function($scope, $location, $firebaseAuth,Authentication){
	
	$scope.login = function() {
		Authentication.login($scope.user)
	} //login

	
});

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply