Reputation: 176
I want to create two separate instances from a service as in this plunkr.
But it seems they share their members. What am I doing wrong?
angular.module("App", [])
.service("service", function() {
var $this = this;
this.number = 1;
var getNumber = function() { return $this.number; }
var setNumber = function(n) { $this.number = n; }
this.build = function() {
return {
getNumber: getNumber,
setNumber: setNumber
}
}
}
})
.factory('fac1', function(service) {
return service.build();
})
.factory('fac2', function(service) {
return service.build();
})
Upvotes: 1
Views: 39
Reputation: 48968
Have your service's build
function create a new object and return the new object.
angular.module("App", [])
.service("service", function() {
var number = 0;
var getNumber = function() { return this.number; }
var setNumber = function(n) { this.number = n; }
this.build = function() {
var newObj = {};
number += 1;
newObj.number = number;
newObj.getNumber = getNumber;
newObj.setNumber = setNumber;
return newObj;
}
})
As mentioned in another answer, both a factory provider and a service provider are singletons. In fact all AngularJS providers are singletons. But a singleton can serve as a "factory" that manufactures a class of objects.
Upvotes: 2
Reputation: 16435
It seems that you're confused about how factories and services work.
Both factories and services are singletons, and moreover they both do basically the same thing. More reading here
fac1
and fac2
are using the same exact instance of service
which means that the member sharing is actually the expected behavior.
Perhaps a solution to your problem would be creating a class inside of your service and returning a new instance of that in your build method.
Then you could do something like:
angular.module("App", [])
.service("service", function() {
var $this = this;
function myClass() {
this.number = 1;
}
myClass.prototype.getNumber = function() { return $this.number; };
myClass.prototype.setNumber = function(n) { $this.number = n; }
this.build = function() {
return new myClass();
}
}
})
if you're unsure how classes work in javascript you could take a look here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
Also another thing to note. If all your factories are doing is returning your service then you probably don't need your factories at all. Just directly use your service's build
method.
Upvotes: 1