Can the merging of this service be possible in AngularJS?

Currently, I am loading two JSON files using separate services in the following manner:

app.factory('AventosService', function($rootScope, $http)
{
  var data = [];
  return {
    promise: null,
    loadAventosJson: function()
    {
      this.promise = $http.get('resources/json/aventos.json',{timeout:20000}).then(
      function(response)
      {
        data = response.data;
        $rootScope.$broadcast('AventosJsonLoaded');
      },
      function(data)
      {
        log('ERROR: ' + data.status);
      })
    },
    getAventosJson: function()
    {
      if (!data.length && !this.promise) this.loadAventosJson();
      return data;
    }
  }
});

app.factory('PartsService', function($rootScope, $http)
{
  var data = [];
  return {
    promise: null,
    loadPartsJson: function()
    {
      this.promise = $http.get('resources/json/part_numbers.json',{timeout:20000}).then(
      function(response)
      {
        data = response.data;
        $rootScope.$broadcast('PartsJsonLoaded');
      },
      function(data)
      {
        log('ERROR: ' + data.status);
      })
    },
    getPartsJson: function()
    {
      if (!data.length && !this.promise) this.loadPartsJson();
      return data;
    }
  }
});

To retrieve the data from the services, I use the following code snippets:

$scope.aventosJson = AventosService.getAventosJson();

and

$scope.partsJson = PartsService.getPartsJson();

I then verify if both events were triggered. These events are AventosJsonLoaded and PartsJsonLoaded

Answer №1

Here is the code snippet for a factory named 'TheService':

app.factory('TheService', function($rootScope, $http)
{
  var data = [];
  return {
    aventosPromise:null,
    loadAventosJson: function()
    {
      this.aventosPromise = $http.get('resources/json/aventos.json',{timeout:20000}).then(
      function(response)
      {
        data = response.data;
        $rootScope.$broadcast('AventosJsonLoaded');
      },
      function(data)
      {
        log('ERROR: ' + data.status);
      })
    },
    getAventosJson: function()
    {
      if (!data.length && !this.aventosPromise) this.loadAventosJson();
      return data;
    },
    partsPromise: null,
    loadPartsJson: function()
    {
      this.partsPromise = $http.get('resources/json/part_numbers.json',{timeout:20000}).then(
      function(response)
      {
        data = response.data;
        $rootScope.$broadcast('PartsJsonLoaded');
      },
      function(data)
      {
        log('ERROR: ' + data.status);
      })
    },
    getPartsJson: function()
    {
      if (!data.length && !this.partsPromise) this.loadPartsJson();
      return data;
    }
  }
});

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 steps can you take to guarantee that a service worker consistently caches the same set of files?

My progressive web app (PWA) is made up of various files like index.html, manifest.json, bundle.js, and serviceWorker.js. Updating the app involves uploading all these files to my host, which in my case is Firebase. I use firebase deploy for this purpose. ...

Angular2: the setTimeout function is executed just a single time

Currently, I am working on implementing a feature in Angular2 that relies on the use of setTimeout. This is a snippet of my code: public ngAfterViewInit(): void { this.authenticate_loop(); } private authenticate_loop() { setTimeout (() =& ...

Problem with jQuery Window Resize Trigger Not Reactivating

I am facing a challenge in integrating a slider within multiple jquery tabs. As the slider requires specific width and height to display correctly, I have to trigger a window resize event when the tabs are switched. Surprisingly, the code I implemented onl ...

Color Your Plone Website with a Custom JavaScript Colorscheme

Currently, I have implemented a custom theme by registering the javascript in the skin.xml file and then creating a specific folder within the browser to store the script. Below is the script shared by one of the users: $(document).ready(function(){ ...

Attempting to fetch JSON information but encountering an error message stating "not a valid function."

I have been working on developing a programmer job board app and I am currently facing an issue with displaying JSON data on the main page. My goal is to eventually render the data, but for now, I just want to ensure that it appears in JSON format so that ...

The program encountered an issue with accessing the 'ref' property, as it was not defined

While creating a basic web app using Vue, Firebase, and Vuefire, I encountered an issue where I received an error message saying "Uncaught TypeError: Cannot read property 'ref' of undefined" when attempting to access my Firebase db variable withi ...

Update the useMemo state value after the initial function block has been executed

Currently, I have a list of characters from Dragon Ball Z that users can filter based on gender, race, or both using useMemo. let dbzCharacters = useMemo<CharacterObj[]>(() => { if (filterGenderValue && filterRaceValue) { retur ...

When the checkbox toggle is marked as checked, ensure that an input field within the toggle div is set as

Utilizing a script to toggle various div elements with JavaScript, I am seeking a way to designate certain input fields as "required" within the toggled div when a checkbox is checked. Can anyone provide guidance on how to achieve this functionality? fu ...

Creating new Vue components is happening towards the end of the loop

I am currently encountering an issue with my Vue components. I have structured them in a hierarchy where I have a post-index component displaying all posts, containing a post-view component for individual posts, and within that, a post-like component to ha ...

Adjusting the size of text in KineticJS to ensure it fits comfortably within a rectangle while

Check out this link: http://jsfiddle.net/6VRxE/11/ Looking for a way to dynamically adjust text, text size, and padding to fit inside a rectangle and be vertically aligned? Here's the code snippet: var messageText = new Kinetic.Text({ x: .25* ...

Vue form component triggers the submit event twice

In my current project, I am utilizing the most recent version of Vue 3 without any additional vendors. After experiencing a setback in which I invested several hours attempting to uncover why my form component was triggering the submit event twice, I am le ...

The LinkedIn API endpoint for accessing client-aware member handles using the query string "handleString" can be found

I am in need of extracting the person ID using the linkedin API https://api.linkedin.com/v2/clientAwareMemberHandles?q=handleString&[email protected] but the response I'm receiving is as follows: { "serviceErrorCode": 100, "messag ...

Is there a way to turn off automatic updates for the timepicker feature?

I am currently utilizing angular-ui-bootstrap for allowing users to input a date. However, the current date is automatically inserted and I am looking to disable this feature. Is there a way to do this? Thank you in advance EDIT1: <uib-timepicker ng- ...

Tips on duplicating an object within a React state without using references

In my React application, I have a state that contains several objects. I need to make a copy of the c: "value" field from the initial state before it gets replaced by the input value from e.target.value. The purpose behind this is to ensure that ...

Guide on retrieving URL data using Ajax

While I am familiar with the method in PHP (e.g. curl) to retrieve the contents of a URL, I am unsure of how to do so using ajax. Unfortunately, I have tried writing code without success in displaying the contents from the URL and separating them into vari ...

Using PhantomJS to extract data from an ASP.NET website that features a dynamic combo dropdown box

I am attempting to scrape this particular page that is coded in ASP.NET and contains 7 dynamic combo drop down boxes using PhantomJS v1.9.8. The JavaScript code I am using is as follows: var page = require('webpage').create(); console.log(&apos ...

Navigate the user to various pages in a Node.js application based on login status

Looking for guidance on a login system within my application? I need to redirect users based on their roles. Below is the code for the login controller, along with node.js snippets and the login HTML page. Any help would be appreciated. Login.html - < ...

Match one instance of a character in a regular expression pattern while simultaneously matching two occurrences of a different character

I am attempting to create a function that can match one occurrence of a certain character and two occurrences of another character simultaneously. For instance, in the string "_Hell_o", I want to match the first underscore (_) and in the string "++Hello", ...

Can you explain the significance of the syntax "require: ^"?

Can someone explain the significance of the ^ symbol under require in this Angular directive code snippet? I came across this code and am having trouble understanding its meaning. .directive('accordionGroupHeading', function() { return { ...

Is the website failing to load on certain IOS devices? Could it be experiencing the dreaded "white screen

Issue Description I have developed an application that is hosted at . Unfortunately, the app does not render correctly on certain IOS devices. I have tested it on my iPhone 5 running IOS 10.3.3 and a friend's iPad with unknown iOS version. The page s ...