The promise from the angular $http function is being duplicated

As I work on evaluating an expression within an if statement to return either true or false, I am utilizing $http promises. Despite the abundance of documentation available on this topic, I am confident in my ability to resolve any issues that may arise.

An interesting observation caught my attention: it appears that the .success callback is executing twice. When I check the console, I can see the output from the success callback appearing twice, indicating a duplicate log of "the call was a success". This led me to wonder why this repetition is occurring.

Upon reviewing the code, it seems that when save() triggers securityCheck.checkLogin(), it logs undefined initially as the promise hasn't been returned yet. Subsequently, the if statement evaluates to false, leading to the logging of "function returned false". Finally, the promise returns with "the call was a success" being logged once. But why does it show up twice in the console?

script

angular.module('login', ['security'])
.directive('loginDirective', ['$parse', 'securityCheck', function($parse, securityCheck) {
    return {
    scope: true,
    link: function(scope, element, attrs, form) {
      scope.save = function() {
        console.log(securityCheck.checkLogin());
           //evaluates to undefined, promise not returned yet
        if (securityCheck.checkLogin()) {
          console.log("function returned true");
        } else {
          console.log("function returned false");
        }
      }
    }
    };
}]);

angular.module('security', [])
.factory('securityCheck', ['$q', '$http', function ($q, $http) {
    var security = {
    checkLogin: function() {
        $http.get('https://api.mongolab.com/api/1/databases/lagrossetete/collections/avengers?apiKey=j0PIJH2HbfakfRo1ELKkX0ShST6_F78A')
            .success(function(data, status, headers, config) {
                console.log('the call was a success!');
            })
            .error(function(data, status, headers, config) {
                console.log('the call had an error.');
            });
    }
    };
    return security;
}]);

html

<html ng-app="login">
  <body>
    <login-directive ng-click="save()">click me</login-directive>
  </body>
</html>

plnkr: http://plnkr.co/edit/tM7eHniDRvCLhzAw7Kzo?p=preview

Thanks!

Answer №1

It's important to note that the checkLogin() method is being called twice:

 console.log(securityCheck.checkLogin());
    //evaluates to undefined, promise not returned yet
 if (securityCheck.checkLogin()) {

This results in the $http.get() being executed twice, along with your implementation of success.

Answer №2

To resolve the issue, you should remove the line

console.log(securityCheck.checkLogin());
so that the request is only issued once. However, this is just a minor problem with your code. The real issue lies in treating the AJAX request as synchronous when it is actually asynchronous. The checkLogin method does not return true/false, but rather a promise object.

You must check for the authentication result within the then callback:

link: function(scope, element, attrs, form) {
  scope.save = function() {
      securityCheck.checkLogin().then(function(check) {
        if (check) {
          console.log("function returned true");
        } else {
          console.log("function returned false");
        }
      });
  }
}

Additionally, ensure that the factory method returns a promise:

angular.module('security', [])
.factory('securityCheck', ['$q', '$http', function ($q, $http) {
    var security = {
    checkLogin: function() {
        return $http.get('https://api.mongolab.com/api/1/databases/lagrossetete/collections/avengers?apiKey=j0PIJH2HbfakfRo1ELKkX0ShST6_F78A')
            .success(function(data, status, headers, config) {
                console.log('the call was a success!');
                return data;
            })
            .error(function(data, status, headers, config) {
                console.log('the call had an error.');
            });
    }
    };
    return security;
}]);

See the demo here: http://plnkr.co/edit/Kj8PkLMv3PsLfe9fsaRo?p=preview

Answer №3

The console.log is invoked twice, once within the directive and again in the service function.

// Execution within the directive
scope.save = function() {    
    console.log(securityCheck.checkLogin());

// Followed by a call within the service
.success(function(data, status, headers, config) {
            console.log('the call was a success!');

Although they serve different purposes, both commands yield the same result

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

Conceal elements with a single click of a button

How can I use jQuery to hide all li elements with an aria-label containing the word COMPANY when the Search from documents button is clicked? Here is the HTML code: <ul class="ui-autocomplete ui-front ui-menu ui-widget ui-widget-content" id="ui-id-1" t ...

Using React to access the properties of objects within an array that has been dynamically mapped

For my initial dive into developing a React application, I am currently in the process of fetching data from a database and updating the state to store this information as an array. My main challenge lies in accessing the properties of the objects within t ...

Troubleshoot: Node Express experiencing issues reconnecting to ajax

Here is the initial question that needs to be addressed. I am currently developing an API that links a front-end application (built using node, express, and Ajax) with a Python swagger API. The issue I am facing is that although I can successfully send da ...

Obtain personalized results for implementing in Convase JS from a PHP server

I have a table on my WordPress site with the following output: { { [line1]=> array(3) {{'x'=>'5' , 'y'=>'8},{'x'=>'5' , 'y'=>'8},{'x'=>'5' , &apos ...

Bizarre Angular directive nesting issue discovered after upgrading from version 1.4.9 to 1.5.0

Forgive the unclear title; I am still trying to pinpoint exactly what is causing issues after the upgrade. Could it be a problem with nested directives or template inconsistencies? (see sample images & links to CodePens below) Issue I have a basic o ...

How to target a class in jQuery that contains two specific strings

There are multiple images in my HTML, each assigned two classes. Here's a snippet of the relevant code: class = "thing other0-a" class = "thing other1-a" class = "thing other2-a" class = "thing other3-a" class = ...

Scheduled Job unable to complete post request

(I am completely new to the world of JavaScript, node.js, and Heroku so I apologize in advance if my question is not very clear) I recently set up a Heroku node.js application with a scheduled task that should run every hour. The task does run as expecte ...

Retrieve live data from a Python script using jQuery and PHP for immediate usage

How can I show the current temperature on a webpage? My setup involves using a Raspberry Pi 3 with the Jessie OS and Chromium as the browser. To achieve this, I have placed a Python script inside a loop for a countdown timer. The script is triggered ever ...

JavaScript failing to accurately measure the length

Currently experiencing a Javascript issue where the length of an element is not displayed correctly when using .length, even though it shows up in Chrome console. Here is what it looks like in Chrome console <html xmlns="http://www.w3.o ...

Code remaining stable post-execution of promise

I'm facing a problem with my Node.js application where I'm using promise-mysql and bluebird packages to make calls to a MySQL database. Despite following tutorials and successfully querying the database, I keep encountering a timeout error. The p ...

What is the best way to make a Dojo TitlePane overlap using CSS?

My dilemma involves a jsfiddle featuring two TitlePane widgets in the central pane's top right corner. Currently, clicking on the right TitlePane ("Switch Basemap") moves the left TitlePane ("Map Overlays") to the left. What I want is for the right Ti ...

What is the process for incorporating an animated gif into a scene?

I'm trying to incorporate an animated gif in three.js. What's the best way to do it? var materialTextured = new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture('images/pin.gif'), transparent: true, ...

Implementing a Beveled Edge on a Shape using ThreeJS

I have put in a lot of effort to find the solution, but unfortunately I have not been successful so far. Currently, I am working on creating a shape using THREE.Shape, and I have the vertices data stored in a file. The shape appears to be straight without ...

The Google Maps feature is not appearing on the webpage as expected

I'm currently working on a website that features a footer with a Google Map. The homepage displays this footer without any issues: However, in other pages, I've implemented the footer by calling it from an external file using jQuery as shown bel ...

Does using AJAX with jQuery and PHP guarantee that the response will always be in JSON format?

While working on PHP validation with AJAX requests for user-submitted information, I encountered an issue. The problem arises when attempting to convert the JSON response from PHP to a Javascript object, as it throws the following error: "Uncaught SyntaxE ...

AngularJS - Array binding issue not updating in directive

I am currently developing a directive that has the ability to display a series of controls. Each individual control is implemented as a directive named fsFilter. In the controller managing the parent element, I establish a binding between the filters arra ...

Having trouble with refreshing the div content when using jQuery's $.ajax() function

My goal is to refresh a div that has the id #todos after saving data in the database. I attempted to use .load() within $.ajax() $('.todo--checkbox').change(function () { let value = $(this).data('value'); $.ajax({ url: ...

The Discord.js .cleanContent attribute does not show up when using Object.keys() and cannot be logged

My Discord.js Message object should contain a property called .cleanContent, according to the documentation, and it should be a string. console.log(message.cleanContent) works correctly, but console.log(message) does not display the cleanContent propert ...

Using NodeJS to handle server side FormData

Currently, in the process of building a web application with nodejs on the server-side, I am facing a challenge of transferring PDF files from the client to the server. Client side: var files = new FormData(); var count = 0; $('#tableSlideId tr&apos ...

What causes the discrepancy between the values returned by the jQuery getter css() method and JavaScript when accessing the style variable

After recently beginning to use jquery, I decided to switch due to initialization issues when loading external styles with javascript. Here is a rule defined in an external style sheet: #siteLogoDiv { position:absolute; left:0px; top:0px; width:100%; heig ...