Strategies for Mitigating Duplicate Requests in AngularJs with just one click

I am facing an issue with my AngularJS application where clicking on a link triggers the API call twice. I'm not sure why this happens and how to fix it.

My service: SomethingService

 function getData() {
    return apiSettings.getApiInformation().then(function (response) {
        var url = response.data.Url + "/odata/Something?$expand=Something";

            var data = {
                url: url,
                type: "GET",
                token: response.data.Token,
                data: {},
                async: true,
                cache: false,
                headers: {
                         "accept": "application/json; charset=utf-8",
                         'Authorization': 'Bearer ' + response.data.Token
                       },
                dataType: "json",
                success: {},
                error: {},
                complete: {},
                fail:{}
            };
            return $http(data);
    });   
}

Api Settings :

angular.module('myApp.services')
.factory('apiSettings', apiSettings);

apiSettings.$inject = ['$http'];

function apiSettings($http) {
    return {
            getApiInformation: function () {
               return $http.get(baseUrl+ '/api/GetApiInformation', {cache: true});
            }
    }

}

SomethingController:

var vm = this;
function getSlots(filterCriteria, selectedValue) {

    somethingService.getData().then(function (response) {
        if (response && response.value.length > 0) {               
            vm.someData = response.value;
        }
    });

View: Clicking on a link triggers getSlots, which results in duplicate requests being sent.

 <a ui-sref="something" class="action-icons" id="slotNav"><i class="fa fa-square-o fa-fw"></i>
something
</a>

This view displays data

<div ng-repeat="data in vm.someData">
        <p> {{data.Name}}</p>
 </div>

Issue: When triggering once, the browser sends duplicate requests as seen below. The first call does not have a callback, while the second one does:

someuls?$expand=something&_=1432722651197   
someuls?$expand=something&_=1432722651197

Answer №1

After encountering a similar issue, I was able to solve it by following the instructions in this helpful answer. In my case, I had mistakenly declared "ng-controller" both in the HTML and using routeProvider, which caused conflicts. The problem was resolved by removing the "ng-controller" property from the HTML code.

I hope this information proves useful to others facing the same dilemma.

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

Is it possible to access forms and input fields in an AngularJS script without having to pass them from the HTML code?

Seeking a solution for input field validation, I have written code where input field states are passed from HTML to a script through a function. However, my goal is to directly retrieve the values in the script without passing them from the HTML when calli ...

Revamp the website's design

I am looking to revamp the color theme of my website with just a click of a button. Can someone provide me with a link to a reference website where I can get some inspiration? ...

How come useEffect runs only once even when multiple states in the dependency array of useEffect change simultaneously?

<div onClick={() => { updateValue1((x: number) => x + 1); updateValue2((x: number) => x + 3); }} > one? two? </div> const [value1, updateValue1] = useState(1); const [value2, updateValue2] = useState(1 ...

How to add a jQuery function to a Rails 3 if statement?

I followed a Rails 3 tutorial on creating a multi-step form which you can check out here. Additionally, I incorporated Stripe payment functionality in my app using another railscast found here. Within my application, the payment form is hidden using jQuer ...

Is it expected to conceal children who are 2 years old?

I came across the following HTML code snippet: <ul id="product_create-header" class="stepy-header"> <li id="product_create-head-0" class="stepy-active"> <div>Categoría</div><span>Categoría</span> </ ...

Using props as classnames in next.js applications

I am currently attempting to create a dynamic header for each page of my app that changes color based on the current page. Here is my approach: <Header className="headerBitcoin"></Header> My goal is to have the same header component ...

Difficulty in using window.scrollTo within useEffect in reactJS

I'm facing an issue where I am trying to use window.scrollTo on the initial render using the useEffect function. I have stored the vertical offset as an integer in localStorage, but the scrolling is not working and remains at position 0. Problem with ...

The message "In Angular, there is no such property as 'data' in the type '{ user: User; session: Session; error: ApiError; }'."

Here is my complete supabase.service.ts code: import { Injectable } from "@angular/core"; import { createClient, SupabaseClient, User } from "@supabase/supabase-js"; import { BehaviorSubject } from "rxjs"; import { envi ...

Resizing an image based on the coordinates of a click position by utilizing jQuery

I'm new to experimenting with code, and I've been playing around with trying to shrink an image to nothing at a central point. I've found some success using a mix of the code snippet below and relative positioning in my CSS. $(function() ...

How to trigger a force reload on a VueJS route with a different query parameter?

Is there a method to refresh the page component when two pages utilize the same Component? I have encountered an issue where the router does not reload and the previous edit values persist. { path: "/products/new", component: ProductPage, meta: { ...

How to automatically refresh a page when the URL changes with Next.js router?

On my page, users have the option to narrow down their search using filters. However, there is an issue where if a user selects a filter for "rent" or "buy", the URL does not automatically refresh to reflect the changes. Even though the changes are reflect ...

Utilizing the Django object array in AngularJS – a comprehensive guide

I have a Django variable structured like this: [<Topic object>, <Topic object>] When passing it to Angular using ng-init, I wrote the following: <div class="profile-navigation" ng-init="ProfileTopics={{ProfileTopics|safe}} "> However, ...

Transfer an array via Ajax to a Python server script

I need to send the names, values, and labels of my form elements when a button is clicked. Since the submit button messes up the order, I decided to handle it with JavaScript: $('#mybutton').click(function() { m.modal('show'); ...

It is important to ensure that the user returned by the onAuthStateChanged function in

server admin.auth().createCustomToken(uuid) .then((customToken) => { admin.auth().createUser({ email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed989e889fad88958c809d8188c38e8280">[email protected] ...

JavaScript Page Search - Error in Finding Single Result

I am currently working on implementing a 'find in page' search box and have come across some JavaScript code that is working really well. Everything works great when there are multiple strings, as pressing enter cycles through the results and the ...

Adding the AJAX response to an array within the AngularJS framework

I am currently working on a function that involves array objects. $http({ method: 'GET', url: 'select.php' }).then(function success(response) { alert(response); //$scope.posts=response.data; ...

Tips for organizing data and dynamically linking options to another select value?

One of my challenges involves working with two select elements. The first select allows for multiple options, while the second select is dependent on the choice made in the first one. <select class="form-control" id="select1"> <option value=""& ...

Enter information into the TextArea and jQuery dialog

I require assistance in populating a textarea with data obtained from querying a database. I have a jQuery dialog that contains another dialog, inside of which is a textarea. Here is some pseudocode: <MODAL> <modalB> <TextArea>s ...

Fade away a division with content C, and Fade In the identical division with content D

Here is the script I currently have: $(function() { $('.ajaxloader').click(function(event) { var target = $(this).attr('href'); window.location.hash = target; $('#conteudoInscricao').fadeOut( ...

The issue with using Angular's form.fieldName.$invalid within the ng-class attribute

After spending some time, I finally figured out the mistake I made in solving this problem. It was a simple error that caused my Angular validation to not work as expected. In order to help others avoid making the same mistake, I decided to share it here. ...