Creating a subclass factory in AngularJS that includes unique member variables

I have a multitude of AngularJS Factories that share similar characteristics. To streamline my code, I am attempting to create a base class and then subclass it.

However, I've encountered an issue where the subclasses are inadvertently sharing member variables with the base class.

To illustrate this problem, I have provided an example on http://jsbin.com/doxemoza/2/edit. You can also view the code below:

HTML:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body ng-app="demo" ng-controller="MainCtrl">
  <p>ChildService: {{value1}}</p>
  <p>AnotherChildService : {{value2}}</p>
</body>
</html>

JavaScript:

angular.module('demo', []);

var demo = angular.module('demo').controller('MainCtrl', function ($scope, ChildService, AnotherChildService) {
  $scope.value1 = ChildService.getPrivateVar();
  $scope.value2 = AnotherChildService.getPrivateVar();
});

var Base = function () {

  var Service = {};

  Service.privateVar = 0;

  Service.setPrivateVar = function (value) {
    Service.privateVar = value;
  }

  Service.getPrivateVar = function () {
    return Service.privateVar;
  }

  return Service;
};

demo.factory('BaseService', Base)


demo.factory('ChildService', function (BaseService) {
  var ChildService = Object.create(BaseService);
  ChildService.setPrivateVar(1);
  return ChildService;
});

demo.factory('AnotherChildService', function (BaseService) {
  var AnotherChildService = Object.create(BaseService);
  AnotherChildService.setPrivateVar(2);
  return AnotherChildService;
});

In my desired output, I expect:

ChildService: 1

AnotherChildService : 2

However, the actual output is:

ChildService: 2

AnotherChildService : 2

It appears that both ChildService and AnotherChildService are sharing the same privateVar, resulting in the duplication of values.

How can I modify the code to ensure that they utilize separate instances of privateVar? Any suggestions would be greatly appreciated.

Thank you

Answer №1

After encountering a similar issue, I found a solution by defining my BaseService as shown below:

app = angular.module('app', []);

app.factory('BaseService', function(){
  return {
    privateNumber: 0,

    setPrivateNumber: function (value) {
      this.privateNumber = value;
    },

    getPrivateNumber: function () {
        return this.privateNumber;
    }
  }
});

The "child" services in my application follow a structure similar to yours and everything is functioning perfectly.

Answer №2

This example illustrates how I structured my code:

angular.module('app')
.controller('ParentController', ['$scope', 'dataService', function ($scope, dataService) {
   //logic for parent controller
}])
.controller('ChildController', ['$scope', '$controller', 'SomeDataService', function ($scope, $controller, SomeDataService) {
//extending the parent controller
    $scope.init = function () {
        //perform actions here
    }
    angular.extend(this, $controller('ParentController', {
        $scope: $scope,
        dataService: SomeDataService
    }));
}])
.factory('BaseDataService', ['logger', function (logger) {
  var privateArray = [];

  return {
   publicFunction: function(){ return privateArray; },
   publicVar: "some variable"
  }
}])
.factory('SomeDataService', ['BaseDataService', function (dataService) {
    var service = angular.extend({}, dataService);
    service.privateFunction = function () {
        //execute specific code
    }
    service.privateVar= "another value";
    return service;
}]);

I have integrated all these components in a coherent manner.

Feel free to refer back to this structure if needed.

Note: This implementation follows the mixin pattern detailed in this post

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring APIs through Angular components: How to effectively test them

I have recently delved into the world of testing angular projects. While basic unit testing seems to be going smoothly for me, I am encountering difficulties with dependency testing, especially when API services are injected into the component and there is ...

Deciphering the creation process behind the "WhatsApp Web" front-end page

I'm currently exploring the creation process of the front-end page for WhatsApp Web, specifically focusing on the list of contacts located on the left side (<div id="pane-side">). The contact names within this list are identified by the class "e ...

Dormant versus dynamic PHP MySQL operations

I am facing an issue where the state doesn't change from active to inactive or vice versa when I click on it. Below is my code for ajax: <script src="//code.jquery.com/jquery-1.10.2.min.js"></script> <script type="text/javascript"> ...

JavaScript is able to access the HTML content of the previously opened tab when saving the window

Seeking advice from the knowledgeable community at Stack Overflow! I have a project that I'm unsure how to start, and I could use some fresh ideas. My goal is to access the HTML source code of a previously opened tab or one that is still loading on m ...

Parent Directory Injector: Prioritizing Injection of Parent Directories

Currently, I am utilizing 'grunt-injector' to inject a list of files using 'app/**/*.js'. However, I am facing dependency errors due to the alphabetical order in which the files are injected. To avoid these issues, I am looking for a so ...

Discover Headphones with Ionic

Is there a way to detect if headphones are connected to a mobile device (specifically an iPhone) using Ionic? Our Ionic app plays sound normally without headphones, but encounters issues when headphones are plugged in. When you start the app without headp ...

console rendering duplication in React

Why am I seeing duplicate log entries in the console? While working on another project, I noticed that the number of HTML elements being added using jQuery was twice as much as expected (specifically while building a notification framework). To investigate ...

Steps for choosing a row from a dynamic table when clicking the mouse

Is there a way to retrieve a row's value upon mouse click or by checking the checkbox in the provided HTML table? Below is the JavaScript code for fetching values from a table using Spry, sourced from an XML file: var ds1 = new Spry.Data.XMLDataSet( ...

Sending information (prop) from _app.js to getServerSideProps in a page on the most up-to-date version of NextJS

I have a unique custom _app.js that I created: const CustomLayout = ({ children }) => (children); const myApp = ({ Component, pageProps }) => { pageProps.url = 'another url'; return ( <CustomLayout> <Co ...

I'm having trouble customizing the appearance of a Tab Panel using the TabsAPI. The panel keeps expanding in strange ways. How can I

Trying to customize the Tabs component from MUI is proving to be a challenge. The main issue I am facing currently is: Whenever I switch between tabs, they appear to expand in size mysteriously. This behavior seems to occur only on tabs with more content ...

Enhance storm-react-diagrams with the powerful features of react-vis

I recently created a customized storm-react-diagram Node and added it to my engine like so: this.engine.registerNodeFactory(new ExampleNodeFactory()); const node2 = new ExampleNodeModel(); const port2 = node2.addPort( new ExamplePortModel("left") ); Wit ...

Learning the process of dynamically binding an id to an HTML tag in Vue.JS

I am currently utilizing Bootstrap Vue for UI and attempting to implement a collapsing feature using this provided link For instance, using v-b-toggle.collapse-2 where the 2 represents a static id. However, I am interested in dynamically assigning this id ...

Adjusting window size when page is resized

While browsing through SO, I stumbled upon this interesting piece of code: var w = window, d = document, e = d.documentElement, g = d.getElementsByTagName('body')[0], x = w.innerWidth || e.clientWidth || g.clientWidth, y = w. ...

Locating the Smallest Value in an Array of Objects

Looking at an object with keys containing arrays of objects that each have a price value. The goal is to find and return the lowest price value. In this scenario, aiming to return the value 8. Wondering if using the reduce method would be the best approach ...

Steps to Hide a Material-UI FilledInput

Trying to format a FilledInput Material-ui component to show currency using the following package: https://www.npmjs.com/package/react-currency-format Various attempts have been made, but none seem to be successful. A codesandbox showcasing the issue has ...

Can you please let me know if it's possible to store an ajax function/call for future reuse?

While developing a web app using JavaScript and PHP, I've noticed that I keep rewriting the same ajax calls repeatedly. Is there a way to create a reusable function or variable for these calls, with or without parameters? I'm fairly new to JavaS ...

How do you invoke a function from within another function in AngularJS?

I'm facing an issue with a function that needs to be called every time a page is loaded. I attempted to achieve this by using the following code: callFunction(); function callFunction(){ $scope.onClickModel(); } ...

What is the best way to retrieve an array of objects from Firebase?

I am looking to retrieve an array of objects containing sources from Firebase, organized by category. The structure of my Firebase data is as follows: view image here Each authenticated user has their own array of sources with security rules for the datab ...

Despite the correct value being displayed in the console.log, the Textfield is not responding to the Reducer

I am currently working on a project to create a tool that can iterate through the pupils of a school class. In order to achieve this, I have implemented a text field in a react component that displays a value: <input className="form-control" onChange={ ...

Module Express - Transferring Object to Main Application

Having issues with passing an object in Express from a module to my application. The process is straightforward - gathering input from a form, validating the string, and returning either null or an object. Despite trying various methods, I'm still fac ...