Making an API call in a getter function using AngularJS

Recently, I came across a project in AngularJS that had some structural issues. One of the main problems was related to fetching settings from an API endpoint. There were times when the application tried to access these settings before they were fully loaded, leading to errors showing up as 'undefined.'

To address this issue, I made use of a getter function. The concept behind it was simple - whenever a method wanted to access the settings object, it would first check if the data had been retrieved from the API. If not, it would make a call to fetch the required information.

After spending some time on it, I managed to get it working. However, there was a flaw in this approach. In cases where multiple methods simultaneously accessed the settings (such as during the page load), the API was hit multiple times because the initial request hadn't finished loading the data into the internal _settings variable yet.

    vm._settings  = null;
    Object.defineProperty(vm,'settings',{get: function(){
      if(vm._settings == null){
        settings_service.get().$promise.then(function success(response) {
          vm._settings = response;
          console.log(vm._settings);
          console.log("returning in");
          return vm._settings;
        }, function error(err) {
          handle_api_error(ngNotify, err);
        });  
      }
      else return vm._settings;
    }});

I'm currently stuck on finding a way to make other attempts to execute the getter function wait until the initial call returns and then utilize that result. I am unsure whether I should explore using await, promises, or any other technique. Your assistance on this matter would be greatly appreciated. Thank you.

Answer №1

If you're looking to optimize these requests, consider implementing a debounce function. You have the option of utilizing an existing library or creating one from scratch.

app.factory('debounce', function($timeout) {
    return function(callback, delay) {
        var timer = null;
        return function() {
            $timeout.cancel(timer);
            timer = $timeout(function () { 
                callback.apply(this, arguments); 
            }, delay);
        };
    }; 
});

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

mdDialog confirmation button malfunctioning

I have been trying to implement Angular Material based on the official documentation, but I am facing issues. The mdDialog doesn't seem to be working as expected and it skips straight to my cancel function without displaying anything. Below is a snip ...

Sending multiple AJAX post requests in succession

I'm encountering an issue with my AJAX POST request for a login form. Every time I submit the form, regardless of whether the combination is correct or incorrect, it sends multiple requests Incorrect login: function incorrect() { $('#loginM ...

Exploring Grafana Panel Development: Harnessing external libraries in plugin development

I'm currently exploring the use of three.js to generate visually engaging images using metrics. As a beginner in Grafana development, I'm facing challenges in determining the ideal time and location to load three.js along with other JavaScript fi ...

JavaScript UDP pinger timeout using the dgram module for nodejs

Currently, I am enrolled in a course where we are tasked with coding a UDP pinger using Javascript with Node.js and Dgram. The assignment provided to us is as follows: Our objective is to create the client-side code for an application. This client should ...

Incorporating isotope with the stylish fancybox

Hello, I am a French speaker so please excuse any mistakes in my English. I hope my explanations are clear: I have been trying to integrate Fancybox2 with isotope, but despite extensive research, I am still unable to get them to work together. The issue I ...

Jimdo: Generate a spinning sliced circle with the click of a button

I'm attempting to achieve a spinning CD/Disk effect when the play button is clicked. I have a sample code below that represents the player's state during playback. What I envision is an image with a play button on top. Upon clicking the button, ...

Trouble arises when using both jQuery and JPagination as JPagination does not function properly

Having trouble getting JPagination to work with a <div> containing <li> elements. Unsure if it's an ID conflict, PHP-related issue, or something else entirely. Would appreciate any help in figuring out the problem. Here is the setup. The ...

Adjusting the z-index of an element with a simple click

Trying to tackle the challenge of adjusting the z-index of "content" relative to a clicked "menu-item". Progress has been made for menu items, but coming up short on the rest. In essence, clicking #m1 should set Z-Index 10 for #c1 and so forth. HTML < ...

Issue with ng-repeat causing HTML table data to not appear

Trying to create a Flask web app, I encountered an issue while attempting to display tabular data on my webpage using AngularJS. Despite using ng-repeat to iterate through the data, it doesn't seem to work and no errors appear in the console. Can anyo ...

Tracking mouse positions across an HTML document

I've been working on a project inspired by the voxel painter example on the three.js page. In this particular example, the mouse coordinates are utilized to move a roll-over helper that indicates where a box will be placed upon click. mouse.set((even ...

The uploading of a file in NodeJS is not possible as the connection was closed prematurely

When I created a website using nodejs, there was a specific page for uploading images to the server. It worked perfectly fine when tested on my computer. However, upon deploying it to the server, the upload functionality stopped working. Upon checking the ...

Simple steps for integrating JavaScript ads into your WordPress website

Received an advertisement from my client, a 300x250 ad in ad folder consisting of 1 HTML file, 1 JavaScript file, and 1 images folder. Questioning how to integrate these files into the side panel of my Wordpress website's homepage. I've spent a ...

Partial data sent through Ajax to PHP file

Encountering a peculiar issue with Ajax where the entire string data is not being sent to the php script. Here is the string: "<p class="MsoNormal" style="text-align:justify"><b><u><span lang="DE" style="font-size:10.0pt;mso-bidi-fon ...

Setting the attribute dynamically for a select box with multiple choices

In my form, I have multiple choice select boxes styled using bootstrap select. Since the app is developed in Express, I am having trouble retrieving the selected values due to bootstrap select creating a div and a list for user interaction. To tackle this ...

Is there a way to switch the language on the date-picker tool?

My date-picker has a unique set up: <input type="text" ng-readonly="true" class="form-control" datepicker-popup="yyyy-MM-dd" ng-model="filter.FInicial" is-open="filter.controlFInicialAbierto" min-date="minDateIni" max-date="maxDat ...

Error in AngularJS: Unable to access property 'get' as it is undefined

Upon examining my App, I found that it is structured as follows: var app = angular.module('cockpit', ['tenantService', 'ngMaterial', 'ngMdIcons']); The controller associated with my App appears like this: angula ...

Expanding a JavaScript list using HTML inputs

I have a script where a grid dynamically displays a list of words. Is there a way to populate the word list in the grid using HTML? Currently, I am doing this... var listOfWords = ["mat", "cat", "dog", "pit", "pot", "fog"]; Can additional words be adde ...

Make the buttons stretch across the width of the window

When the App is launched, it will display two buttons in the footer by default. If users interact with the app in a certain way, a third button may need to be added. However, based on other user selections within the app, this button may also need to be ...

There seems to be a malfunction in the AngularJS radio button component

I'm working with AngularJS radio buttons and encountering an issue where changing the values results in two models being updated. Can someone take a look at the code snippet below? <input type="radio" name="radio" ng-model="certResults.option1fla ...

Employ various iterations of the leaflet library

Creating a web application using React and various libraries, I encountered an issue with conflicting versions of the Leaflet library. Currently, I am incorporating the Windy API for weather forecast, which utilizes Leaflet library version 1.4.0. However ...