Utilize Services without creating circular interdependencies

My app utilizes a GlobalDataService (GDS) to store all data globally.

GlobalDataService (GDS)

angular
        .module('app.core')
        .service('GlobalDataService', GlobalDataService);
    GlobalDataService.$inject = ['$http', 'LineStatusService'];
    function GlobalDataService($http, LineStatusService) {
        var gds = this;

        gds.data = {
            //all my data
        }

        gds.data.lines = LineStatusService.getLineStatus().then...
    }

In addition, there is a StatusDataService (SDS) responsible for managing the status of the data.

StatusDataService (SDS)

angular
        .module('app.core')
        .service('LineStatusService', LineStatusService);
    LineStatusService.$inject = ['$http', 'GlobalDataService'];
    function LineStatusService($http, GlobalDataService) {
        var service = {
            getLineStatus: getLineStatus,
            saveLineStatus: saveLineStatus,
            ...
        };

        function saveLineStatus (line, status, user) {
            var data = {
                status: {
                    status_id: status.status_id,
                    status_desc: status.status_desc
                },
                updated_by: user
            }

            return $http.post('/api/euauto/v1/delivery-status/linestatus', data)
            .then(function successCallback(response) {
                GlobalDataService.data[id].status = status;
                return response.data;
            }).catch(function errorCallback(response) {

            });
        }

        return service;
    }

The GDS fetches all statuses when the app loads initially, while the Status Service handles other data requests.

To avoid circular dependencies, I plan on letting my Controller handle save and update using SDS while also updating GDS.

Potential Solution

angular
        .module('core')
        .controller('MyController', MyController);

    MyController.$inject = ['GlobalDataService', 'LineStatusService'];
    function MyController(GlobalDataService, LineStatusService) {
        function changeStatus(line, status, user) {
            //do a thing
            //and another
            LineStatusService.saveLineStatus(line, status, user);
            GlobalDataService.data.line[id] = status;
            GlobalDataService.updateAllOtherData();
            //etc...
        }
    }

The Problem

Now that I want to create a new Controller with the same functionality, I realize I have to duplicate the code from the original Controller to reuse both Services. Additionally, if GDS doesn't depend on SDS, it will not be able to fetch line statuses on load, requiring each Controller in the app to do so individually.

Ideally, all logic and requests should be centralized, preferably within SDS. This way, GDS data can remain consistent throughout the entire Application.

Answer №1

If you want GlobalDataService to be initialized with data at the beginning of the app, consider initializing it within a .run() block instead of in the service constructor. This approach avoids the need for other services to be injected into GDS directly. As a result, other data services can safely have GDS injected without encountering circular dependency issues.

angular
    .module('app.core')
    .run(function(GlobalDataService, LineStatusService) {

    GlobalDataService.data.lines = LineStatusService.getLineStatus().then...

});

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

What could be causing the kendo autocomplete to display [object Object]?

I have encountered an issue when trying to update my kendo autocomplete using the code below. It displays [object Object] in the UI. <ng-template kendoGridCellTemplate let-dataItem="dataItem" let-rowIndex="rowIndex"> <kendo ...

Experimenting with Jasmine for testing an AngularJS service without the need for mocks

I am interested in utilizing Jasmine for writing tests (not unit tests) for an AngularJS service that acts as a wrapper for a REST API I developed on my server. The goal is to ensure that the service call reaches the server without requiring any form of mo ...

A step-by-step guide on duplicating the functionality of the jQuery

Issue at Hand: I'm attempting to recreate the functionality of jQuery's ajax method as I find myself utilizing XMLHttpRequest multiple times within a script. However, I am hesitant to include jQuery as a dependency since I only require a few meth ...

JQuery range events failing to trigger

Whenever a user adjusts the JQuery range control, I want to update a value. Despite my attempts to follow an example provided here, I have not been successful. $(document).ready(function () { alert('ready1'); //This alert appears when t ...

The ng-model is failing to identify the value and is remaining undefined

Having trouble passing a variable from an <input> to a function using ng-model within the input. The variable remains undefined no matter what I try. The input field is located inside a <td> and has the following structure: <td> ...

Utilizing HTML5 Video Autoplay with AngularJS ng-show: A Comprehensive Guide

How can I implement a video using the HTML5 video tag with autoplay in an AngularJS web application? I attempted to use the following code: <video ng-show="condition" autoplay ng-src="{{video.src}}"></video> Upon loading the web application, ...

Adding and removing form fields dynamically in a Rails3 application with the help of Jquery

Could someone please share an uncomplicated or the most effective method for dynamically adding fields to a form in Rails3 using JQuery? ...

reference is not accessible within HTMLAttributes for HTMLDivElement

I created a versatile wrapper component with the following structure: import { FC, HTMLAttributes } from "react"; const CustomWrapper: FC<HTMLAttributes<HTMLDivElement>> = ({ children, className, ...props }) => ( <div c ...

Numerous occurrences of Autodesk Forge Viewer

I am facing a challenge in implementing multiple instances of the Autodesk Forge Viewer (v6.2) on my webpage, each hidden within tabs. The goal is to show and hide the viewer with a loaded model as the user switches between tabs. Although I have managed ...

Adding a delay to your JQuery wiggle effect

Is there a way to achieve an effect similar to the JQuery wiggle plugin? Check out this demo: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js" type="text/javascript"></script> <script src="http://static.manpoints.u ...

The Jquery click function seems to be malfunctioning when triggered using a laptop mouse tracking pad, but functions properly otherwise

I am facing an issue on my webpage where I use a typing input to search for certain IDs using the typeahead library from jQuery. Oddly, when I click on the search results that are displayed in a list by an external mouse, everything works perfectly fine. H ...

What is the best way to arrange four divs in a row on a mobile device that is responsive?

I am facing an issue with displaying 4 divs of equal size on my website. In desktop view, they appear side by side but in mobile view, they stack on top of each other. I have tried using display: flex; and bootstrap classes like col-3, col-sm-3, col-md-3, ...

Tips for sequentially calling multiple await functions within a for loop in Node.js when one await is dependent on the data from another await

I am currently facing a challenge where I need to call multiple awaits within a for loop, which according to the documentation can be performance heavy. I was considering using promise.all() to optimize this process. However, the issue I'm encounterin ...

What is the process for obtaining an API Key in order to access a service prior to authorization?

Alright, I have this app. It's a versatile one - can run on mobile devices or JavaScript platforms. Works across Windows, Apple, and Android systems. The app comes equipped with a logging API that requires an API key for operation. Specifically, befo ...

How can I use Java Script to create animation of vertical black bars of a specific width moving across a white background?

Looking for a JavaScript code that can animate vertical black bars of a specific width moving over a white background. The desired outcome is similar to the video found at: https://www.youtube.com/watch?v=bdMWbfTMOMM. Thank you. ...

Simple way to automatically reload your script using an npm server

Testing out a sample javascript code snippet. Locating a script named simple.js in the demos directory. Executing the demo using the command yarn build-demos && http-server demos/ The script simple.js is compiled to simple_bundle.js and the serv ...

Is there a way for me to insert my function into the button so that it can execute upon being clicked

<span>Create Request File for Activation</span> <input type="submit" value="Generate" class="submit" id="submit"/> I'm trying to link my function with the button above. How can I make it so that when ...

Display images fetched using ajax requests

Looking to retrieve the image source path using the code below: $.ajax({ url: 'api/catalogs.php?action=fetchimg&CatalogId=' + d.CategoryId, type: 'GET', dataType: "json", success: function(response) { var path = respo ...

What are the capabilities of Ajax when it comes to utilizing select controls in J

Is there a way to trigger an ajax call when a select control value is clicked? The onChange event doesn't seem to work for me in this case :( This is what I have tried so far: JAVASCRIPT: <script> function swapContent(cv) { $("#myDiv"). ...

Vue.js2 - Detection of Observer in Array

A question for beginners in vue.js. I am trying to display data using the CanvasJS Library that is received via websocket. Everything works fine with the data until I introduce vue components into the mix. Let me clarify: export default { data() { r ...