Calling a parent function within the $http method

I have a system in place that verifies the existence of a serial number within my database.
If the serial number is found, I want the system to provide me with the corresponding barcode. However, if the serial number does not exist, it should return "false".

Unfortunately, the current implementation of my code is not functioning as expected, most likely due to being nested in an inner function.
I attempted to call another function upon receiving a response, but it seems like this approach is not impacting the scope as intended.

Below is a snippet of my code:

  $scope.checkSerial = function(e) {
    if (e.which==9) {
      res = serialChecker.check($scope.itemsData, $scope.serial, e);
    }
  }    

.service('serialChecker', function($log, $http) {
 this.check = function(_itemsData, _serial, e) {
   isok = false;
     // Fetch serial barcode
     config = {
       params: { serial: _serial, action: 'check_serial' }
     };
     $http.get("srvr.php", config)
     .then(function(bcresponse) {
       $log.info("Currently looking at serial: " + _serial);
       barcode = bcresponse.data.barcode;
       if (barcode==false) {
         return false;
       }
       angular.forEach(_itemsData, function(value, key){
           angular.forEach(value.Items, function(value, key) {
             if (value.Codebars == barcode) {
               return barcode;
             }
           });
        });
     });
 }
});

Do you have any suggestions or insights on how to resolve this issue?

Answer №1

$http.get is an asynchronous function that returns a promise, not the actual result of the call. To access the result, you need to chain the then function to the serialChecker.check:

.service('serialChecker', function($log, $http) {
  this.check = function(_itemsData, _serial, e) {
    // Fetch serial barcode
    config = {
      params: { serial: _serial, action: 'check_serial' }
    };
    return $http
      .get("srvr.php", config)
      .then(function(bcresponse) {
        $log.info("Currently examining serial: " + _serial);
        barcode = bcresponse.data.barcode;
        if (barcode==false) {
          return false;
        }
        angular.forEach(_itemsData, function(value, key){
          angular.forEach(value.Items, function(value, key) {
            if (value.Codebars == barcode) {
              return barcode;
            }
          });
        });
    });
  }
});

$scope.checkSerial = function(e) {
  if (e.which === 9) {
    // TODO: show progress indicator
    serialChecker
      .check($scope.itemsData, $scope.serial, e)
      .then(function(res) {
        // TODO: use the result here
      })
      .catch(function(err) {
        // TODO: handle errors 
      })
      .finally(function() {
        // TODO: hide progress indicator 
      });
  }
} 

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

Error Encountered: Module Not Located

I am encountering an error in my Project where it keeps showing 'Cannot find module' even after numerous attempts to install and uninstall packages simultaneously. The problem persists, and I can't seem to resolve it. https://i.sstatic.net/Z ...

AngularJS does not refresh the DOM as anticipated

I have a fiddle demonstrating the geocoding of an address input into a textbox. The issue I'm facing is that after pressing 'enter', the table does not update immediately; it waits for another change in the textbox. How can I make it update ...

What could be the reason for the component bindings being undefined within the controller?

I'm currently working on a basic angular component. I have set up a parameter as a binding and managed to display its value on the screen successfully. The parameter displays correctly, but when I try to access it within the controller, it shows undef ...

If the button is clicked in jQuery, then perform a specific action; otherwise, execute

hello, I am encountering difficulties in getting this feature to function properly. I am utilizing cropbox to allow users to upload their logos. The issue arises when users do not click on the crop button again; it results in overwriting the existing file ...

Crop base64 image data into a circular shape

I am looking to crop a portion of an image that takes up the entire screen. Specifically, I need to capture only a small section of the image, measuring 300px in width and height from the top 25%. Below is an example I came across: In the example, there i ...

Javascript try...catch fails to catch exception

In my Node subroutine, I have implemented a process to load configuration settings before the main application starts. However, if the required file is not found, the exception is not caught properly and ends up breaking the entire application. Here is th ...

Issue with Ionic custom directive functionality in the emulator

As I develop an application using Ionic 1 and custom directives, I've encountered a challenge where the directives work fine in browser testing but fail to appear on the emulator or iPhone. Despite trying various solutions suggested by others facing s ...

Creating an input range element and its event handler dynamically within the ajaxStop function allows for real-time updates based on the

As a beginner in JavaScript development and Ajax, I am currently working on creating a webpage that utilizes Ajax to fetch data from a server. The data is then used to draw geoJSON features on a map using Leaflet. These feature sets need to be toggleable f ...

Struggling to fully understand and implement jQuery's click() method, as well as navigate event.data

Currently, I am in the process of developing a small script that allows users to dynamically change the background image of a webpage for design comparison purposes. Although I have a basic version working, I am facing a minor issue that I am determined t ...

The delay between initiating a Next JS route by clicking and the corresponding page actually loading

Just launched my website at this link: I am experiencing a delay of up to 2 seconds between clicking the header links and the page loading. The site works fine in development and on localhost, so I'm not sure why there's such a slowdown on the l ...

Angular 5 combined with the dynamic capabilities of Popper.JS

Launching a training project that requires Popper.Js in its features has been quite challenging. Despite following Bootstrap's documentation on how to implement Popper.Js, I have encountered difficulties. As per Bootstrap's docs, I tried initiat ...

What steps can be taken to proceed with the promise chain following a retry attempt

When using restangular to make multiple calls to the backend, I encountered an issue where subsequent requests are dependent on the result of the first call. To address this, I attempted to implement retry logic to ensure that follow-up requests are execut ...

Animating file transfer can be achieved using either JavaScript or CSS

My goal is to create a visual representation of file transfer, such as moving a file from one folder to another. I have successfully achieved this using JavaScript with the following code: <script type="text/javascript> var img; var animateR; var an ...

Is it feasible to preserve the HTML form content data even after refreshing the page?

Can someone offer a suggestion that doesn't involve using Ajax? I'm wondering if there is a way to achieve this using JavaScript/jQuery or some other method. Here's my issue: When submitting a page, the action class redirects back to the sa ...

Is it risky to replace the default 'console' in node with something else?

As a creature driven by habits, I find myself instinctively using console.log/console.error/etc to print things out. However, in an effort to centralize my logging in node, I am transitioning to 'winston'. My plan is to include var console = requ ...

Attempting to format a number using a computed property and .toLocaleString() fails to execute

I am facing an issue with the formatting of a number displayed in a <p></p> element. The number is coming from a range input element that is bound to an amount data property using v-model. Even though I have a computed property to format the nu ...

Modify the flashVars in flowplayer using swfObject to switch videos

I am currently implementing a cross-browser solution to play .mp4 video files and I need to ensure compatibility with IE8 and newer versions. The approach I am using is referenced from Dev-Metal and so far, everything has been successfully configured and i ...

Starting up an AngularJS controller with varying sets of data

In my Angular app, I am utilizing $routeProvider for routing purposes. There are 2 routes where I am using the same HTML template and controller. when('/products, { templateUrl: 'views/products.html', control ...

The Dropdown Menu and Slick Gallery are not intersecting

In my jQuery Slick Gallery, I have a Dropdown Menu that displays an unordered list of menu entries when a button is clicked. The issue I am facing is that the unordered list is hidden at the bottom edge instead of appearing above the dots as intended. You ...

What is the solution for resolving AngularJS URL encoding?

Currently, my AngularJS app utilizes a component known as navbar to house the searchbar along with a search() function. $scope.search = function (keyword) { console.log(keyword); $state.go('main', { keyword: keyword }, ...