Ways to ensure a particular promise is executed only once in Angular 1.5 despite multiple calls to the onInit hook

When the onInit function is called, an API request is made.

   vm.$onInit = function() {
        var callInProgress = false;
        var resultsLoaded = false;

        var url = '/api/times/cst';
        if(callInProgress === false && resultsLoaded ===false){
            callInProgress = true;
            HttpWrapper.send(url,{"operation":'GET'}).then(function(result){
                vm.times = result;
                resultsLoaded = true;
                },function(error){
                vm.errorInApi = true;
            });
        }

The issue arises from $onInit being called multiple times, causing the flags callInProgress and resultsLoaded to be re-initialized each time.

This repeated check is not effective in preventing multiple API calls when $onInit is triggered.

Despite this problem, the API continues to be called every time $onInit runs during initialization.

How can I ensure that the call is only made once? It must still occur within $onInit.

Answer №1

To optimize the API call, I recommend encapsulating it within a service structure similar to this:

(function (angular) {
    'use strict';

    angular
        .module('services.global')
        .service('TimeService', TimeService);

    TimeService.$inject = ['HttpHandler'];

    function TimeService(HttpHandler) {
        var timeService = this;
        var cachedResult = null;

        timeService.fetchTime = fetchTime;

        function fetchTime() {
            if (!cachedResult) {
                cachedResult = HttpHandler.send('/api/time/utc', {"method": 'GET'});
            }
            return cachedResult;
        }

        return timeService;
    }

})(angular);

Once you have defined and injected this service into your controller, make use of TimeService.fetchTime() in place of making direct API calls. This way, the API request will be made only once during the initial invocation of fetchTime(), storing the response in cachedResult for subsequent usage.

Answer №2

In the onInit function of the directive controller, there are callInProgress and resultsLoaded functions that will be generated every time the directive is used. For a similar functionality in the containing controller, utilizing a controller property would be the recommended approach. By using bindings, you can specify the controller property needed to maintain a sense of generality.

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

Formatting text to automatically continue onto the next line without requiring scrolling through long blocks of

I have a unique Angular project with a terminal interface that functions properly, maintaining a vertical scroll and automatically scrolling when new commands are entered. However, I am struggling to get the text within the horizontal divs to wrap to the ...

Trying to assign marker image dynamically through various database inquiries

With the use of the Google Maps API v3, I am currently displaying a map of the United States with markers placed at specific locations obtained from address queries in my Postgres database. My goal is to customize the marker image based on the result of ea ...

Preserving state values with the useState hook throughout various function invocations

When I click the button to delete department rows from my table, I am using the "deleteDepartment" function. The issue arises when trying to get the selected row index in the "selectedRows" hook. It seems that the "rowSelection" state keeps accumulating va ...

Is it possible to send emails from a local server to Gmail, Yahoo, or Rediff?

Currently, I am developing a feature that allows users to send emails to any recipient including Yahoo and Gmail. Below is the code snippet for my contact form: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1 ...

When an option is selected in one dropdown, a list is dynamically populated in another dropdown. However, the entire column then displays the selected row's options in a table format

https://i.stack.imgur.com/q7tMT.png Upon selecting an option from a dropdown within a table row, I make a call to an API to fetch a list of strings into another dropdown field for that specific row. However, the entire column is being populated with that r ...

Encountering issues with formData in nextjs 13 due to incorrect data type

In my NextJS application, I am using the dataForm method to retrieve the values from a form's fields: export async function getDataForm(formData) { const bodyQuery = { ....... skip: formData.get("gridSkip") ...

Use AngularJS to display content if X is greater than Y and apply a specific class

As I embark on the creation of my first app, it excites me to build an ordering system that allows customers to seamlessly add items to their cart. The functionality is flawless so far. However, my client has expressed the need for a feature that alerts th ...

What is the best way to show the current date and time in an Angular template while ensuring it stays up to

I'm looking to showcase the current date and time in my angular template, and have it automatically refresh when the time changes. The desired application LOOKS as follows: This snippet is from my .html template: <div class="top-right pull-right ...

Exploring javascript Object iteration with arrays using Python

When users click the "done" button on a text box, all input is stored in an associative array and sent to a Python method. The data is then converted to JSON before being sent via AJAX: $.ajax({ url: "http://127.0.0.1:6543/create_device", ...

The error message "Client blackbox not found. undefined" was thrown by wweb.js while trying to retrieve client data from a Map

WhatsApp Client Manager WhatsApp Client Manager Client.js File Client.js File Message Controller Script Message Controller Script Issue Encountered I'm attempting to initialize the client with the code "const client = await clientManager.getClient ...

Creating UI Bootstrap dropdowns using ng-repeat on the fly

As a newcomer to AngularJS and UI Bootstrap, I am facing an issue with adding dropdowns dynamically using ng-repeat. The main problem lies in the fact that when one dropdown is clicked, it triggers all of them simultaneously. It seems like there is some mi ...

Is there a way for me to respond to an APNS push notification by executing a task specified in the payload?

As a newcomer to objective-c, xcode, and app development, I kindly ask for your patience. I have managed to send a push notification via APNS to my new app. I can view the JSON message and log it using NSSLog. Payload: { aps = { alert = { ...

Mastering asynchronous function handling in Node.js

I'm currently experiencing an issue with printing two statements using two functions var mongoose = require( 'mongoose' ); var_show_test = mongoose.model( 'test' ); exports.showTest = function(req,res) { var jsonString = []; ...

How to Use AngularJS $http Mock Respond to Simulate a Response with a `location` Header?

One interesting scenario I have encountered involves an API that returns a status code of 202 with no data. However, the response includes a header called "Location" which points to a specific URL. After browsing through the $httpBackend respond(...) docu ...

Issue with React submit button for posting data is not functioning as intended

My dilemma lies within a Modal component containing a Form and Button. The goal is to trigger a POST request (managed in a separate file) upon the user clicking the button, which will run a simulation using the validated input values. Surprisingly, the onC ...

Is there a way to have the ng-option initialize with the selected object value?

I am attempting to initialize this select element with a preselected option. However, the value I need to use is an object as shown in my code. The id that I require needs to be retrieved from data.selected. index.html <div ng-controller="MyCtrl">{ ...

What could be causing the catch() block to not execute in Objection.js queries, with the then() method always running and returning either 0 or 1 as a result?

When executing a query using Objection.js, the result of the query will be passed to the then() block as either 0 or 1 depending on its success or failure. Instead of handling errors in the catch block, I find myself checking falsey values. Is there a be ...

Express JS causing NodeJS error | "Issue with setting headers: Unable to set headers after they have been sent to the client"

As I embark on my journey to learn the fundamentals of API development, I am following a tutorial on YouTube by Ania Kubow. The tutorial utilizes three JavaScript libraries: ExpressJS, Cheerio, and Axios. While I have been able to grasp the concepts being ...

Mocking a promise rejection in Jest to ensure that the calling function properly handles rejections

How can I effectively test the get function in Jest, specifically by mocking Promise rejection in localForage.getItem to test the catch block? async get<T>(key: string): Promise<T | null> { if (!key) { return Promise.reject(new Error(&apo ...

Scaling a mesh and BufferGeometry vertices using THREE.OBJLoader

Utilizing the THREE.OBJLoader, I successfully loaded a 3D model into my scene. Subsequently, I have the necessity to scale it by 10 and then extract its vertices position. I am aware that the THREE.OBJLoader provides a BufferGeometry, allowing me to acce ...