Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
68
rated 0 times [  70] [ 2]  / answers: 1 / hits: 5439  / 10 Years ago, wed, may 21, 2014, 12:00:00

I am trying to find of a way to extend services in angular. I am not sure if angular has a concept of extending or if it merely relies on injection for code reuse. So what I have tried so far are the following



Method 1



myApp.factory('myFactory', function ($http) {
return{
common: function(){
console.log('I am from myFactory');
}
});


myApp.factory('myFactory1', function (myFactory) {
return {
common: myFactory.common
};
});


OR



 myApp.factory('myFactory1', function (myFactory) {
return angular.extend(myFactory, {
common: function() {
console.log('I am form Factory1')
}
});
});


Both approaches sort of work OK but my main issue is how to call the parent. i.e. something like this:



in myFactory1



     common: function(){
console.log('I am from myFactory1');
this.prototype.common.apply(this, arguments);
}


I want is to print out 'I am from myFactory1', 'I am from myFactory'



Generally Is this supported in angular ? Or should I take a different approach in extending /inheriting functionality?



Thank you


More From » angularjs

 Answers
4

The way I've achieved this in the past is to have the base angular service return an instance of a plain old Javascript 'class'. The extended service, then creates an instance of the base class, and uses standard JS prototypal inheritance to extend the class and returns an instance of the new extended object.



For example:



// Base service
app.factory('Shape', function() {

var Shape = function(colour) {
this.colour = colour;
};

Shape.prototype.getColour = function() {
return this.colour;
};

return Shape;
});

// Extended service
app.factory('Square', function(Shape) {

var Square = function(colour) {
Shape.apply(this, arguments);
};

Square.prototype = new Shape();

Square.prototype.getSides = function() {
return 4;
};

return Square;
});

[#45144] Tuesday, May 20, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
erinh

Total Points: 38
Total Questions: 100
Total Answers: 110

Location: Macau
Member since Mon, Nov 16, 2020
4 Years ago
;