Angular Resolution Verification

I'm currently working on making HTTP calls in Angular and I want to trigger a different service function if an error occurs. The problem is, no matter what the original service call function returns, the promise always ends up being "undefined". Here's some code for better context:

  srvc.sendApplicantsToSR = function (applicant) {
    var applicantURL = {snip};

var promise = $http({
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    method: 'POST',
    url: applicantURL,
    data: applicant
})
  .success(function (data) {
    return data;
  })
  .error(function (error) {
    return [];
  });

  return promise;
  };

Next, in the controller:

for (var applicant in $scope.applicants) {
            $scope.sendATSError($scope.sendApplicantsToSR($scope.applicants[applicant]), applicant);
       }

$scope.sendATSError = function (errorCheck, applicantNumber) {
      if (angular.isUndefined(errorCheck)) {
      console.log(errorCheck);
        AtsintegrationsService.applicantErrorHandling($scope.applicants[applicantNumber].dataset.atsApplicantID);
      }
    };

The issue here is that it always detects errors since every response is undefined. How can I correctly distinguish between the two returns? Appreciate any help provided! Thanks!

Answer №1

After reviewing the angular documentation, I found this example code snippet:

$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // Asynchronous callback for when response is available
  }, function errorCallback(response) {
    // Asynchronous error handling if server returns an error
  });

Given that information, your initial code snippet should resemble this:

 srvc.sendApplicantsToSR = function(applicant) {
     var applicantURL = {
         snip
     };

     return $http({
         headers: {
             'Content-Type': 'application/x-www-form-urlencoded'
         },
         method: 'POST',
         url: applicantURL,
         data: applicant
     });
 };

Answer №2

Like mentioned by others, the use of $http's .success() and .error() methods is no longer recommended in favor of using .then().

In the function .sendApplicantsToSR(), there is no need to chain .then() as you do not necessarily have to process the data or handle errors at that moment.

$scope.sendApplicantsToSR = function (applicant) {
    var applicantURL = {snip};
    return $http({
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        method: 'POST',
        url: applicantURL,
        data: applicant
    });
};

When calling this function in a loop, a promise is returned which will either follow the success path or the error path based on how you set up your callback functions with .then().

To address this correctly, structure your code with $scope.sendApplicantsToSR() on the outside and $scope.sendATSError() on the inside, connected by .then().

for (var prop in $scope.applicants) {
    var applicant = $scope.applicants[prop];
    $scope.sendApplicantsToSR(applicant).then(null, $scope.sendATSError.bind(null, applicant));
}
// Use `null` for success cases and provide a function for error handling.

Passing the applicant parameter simplifies the error handler function, $scope.sendATSError():

$scope.sendATSError = function (applicant) {
    return AtsintegrationsService.applicantErrorHandling(applicant.dataset.atsApplicantID);
};

If you need to know when all promises are settled, consider addressing it separately in another question.

Answer №3

You should make sure to handle your promise within the controller itself.

Simply put:

.factory('myFactory', function() {
    return $http.post(...);
})
.controller('ctrl', function(){
    myFactory()
        .success(function(data){
             // manipulate your data here
        })
})

Here is a practical example:

angular.module('myApp',[])
.factory('myName', function($q, $timeout) {
    return function() {
        var deferred = $q.defer();
        $timeout(function() {
            deferred.resolve('Bar');
        }, 2000);
        return deferred.promise;
    }
})
.controller('ctrl', function($scope, myName) {
    $scope.message = 'Waiting for update.';
    myName().then(function(data) {
       $scope.message = 'Hi '+data+'!';
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ctrl">
    {{message}}!
</div>

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

Cause: Trying to serialize an `object` that is not JSON serializable (such as a "[object Date]"). Ensure that only JSON serializable data types are returned

Currently, I am utilizing Prisma along with Next.js. My issue arises when attempting to retrieve content from Prisma within the getStaticProps function; while it successfully fetches the data, I encounter difficulties passing it on to the main component. e ...

Guide user to different screen in React Navigation depending on context state

In my project, I have introduced a new state called roleSelected. Initially, the value of this state is set to false, and it is managed within my AuthContext. const [roleSelected, setRoleSelected] = useState(false); The configuration of my stack navigatio ...

Next.js is refusing to render an array of HTML elements

Consider this scenario where I have a block of code in TypeScript that attempts to create and display a list of elements. Here is a sample implementation: const MenuList = ():ReactElement => { const router = useRouter(), liElements:any = []; con ...

Discover the best practices for implementing MongoDB's latest Schema Validation functionality within your Express.js application

Need help implementing MongoDB's Schema Validation in an Express server? While working on a simple todo app, I opted for the native MongoClient over mongoose but still require a schema for my data. According to MongoDB's documentation available ...

What is the best way to send two mongoose find queries to the correct GET route?

I am facing an issue with my app where I have two separate routes using app.get to render "/" and fetch data from two different MongoDB collections using mongoose find{} methods. I also have corresponding post routes that redirect the data entered in forms ...

What is the best way to integrate an AJAX callback into the stop condition of a `do while` loop?

Take a look at the code snippet below: let count = 0; do { $.ajax({ type: "POST", url: someurl, dataType: 'xml', data: xmlString, success: function(xml) { count++; } } while(co ...

Tips for resolving the error "Parsing near 'Unexpected end of JSON input while parsing...' for...'mocha':'^3.2.0','s'":

Once I've successfully set up react and react-dom, the next step is to install webpack. However, I encountered an error during this process. To troubleshoot, I decided to install babel-loader first to ensure that both npm and my internet connection a ...

Looking to find the video code in the page source and figure out how to get the video to play

I have a requirement where I must embed the video code directly in a blog post. After figuring out the necessary code for the video and saving it in a html file named video.html, I encountered an issue when trying to upload the file to the blog. Only the ...

Manipulate CSS classes in an ng-repeat list using AngularJS

Dear colleagues, let's take a look at this clear example. [...document.querySelectorAll('.li-example')].forEach((s, i, arr) => { s.addEventListener('click', function() { [...document.querySelectorAll('.li-example&a ...

When examining passwords, Bcrypt returns false

In my application, I am utilizing the Promise interface along with bcrypt. Despite using the same password for comparison, I am receiving a false result. const bcrypt = require('bcrypt'); const saltRounds = 10; const password = 'secret&ap ...

Guide on developing a JavaScript script for implementing across numerous Bootstrap modals within a single webpage

I have been working on setting up a page with 14 different modals. Initially, all the modals were opening normally, but I recently discovered a way to make them draggable when opened. After some trial and error, I managed to implement this feature successf ...

Create sleek and custom forms with AngularJS and JQuery

As a core C++ developer, I have recently expanded my skills to include Scala, Lift, and AngularJS. My latest project involves developing an application similar to . There is a high possibility of needing to modify existing features or introduce new ones t ...

What is the method to activate the ngchange event when a user pastes content into a content editable div by using the right mouse click?

When a user pastes something into my content editable div using the Mouse Right Click and Paste function, I want to trigger a specific function. I currently have an ng-change event bound - if I can trigger that one instead, that would also work fine. ...

The SrollToTop function is ineffective when used with a component in Ionic 6/Angular

Recently, I implemented a fabbutton feature that allows users to scroll to the top of a page with just one click. Initially, I tested this functionality without using it as a component, and everything worked perfectly. However, now I want to turn this fabb ...

Retrieve content from JSON post data

I have been facing an issue where I am trying to send a JSON file from a web page to a nodeJS server. My goal is to assign the JSON file to an object on the server side and print it out in the console. Despite researching extensively online and attempting ...

Is there a way to deactivate the minutes input feature in the Angular UI Timepicker?

I am using a plugin that displays the time in hours and minutes. However, I only need to show the hours. Is there a way to hide the minutes block? This is my HTML code: <uib-timepicker ng-model="mytime" ng-change="changed()" hour-step="1" minute-step ...

JavaScript/CSS memory matching game

Just starting out in the world of programming and attempting to create a memory game. I've designed 5 unique flags using CSS that I want to use in my game, but I'm feeling a bit stuck with where to go next. I understand that I need some function ...

AngularJS File Input element triggering only once when selecting the same file

I have created an Angular directive to customize the file upload input. directive('ngFile', function () { return { link: function (scope, element, attrs) { var button = element.find('button[data-fileInputButton]&apos ...

Injecting variable styles into my VueJS component

I am currently working on developing a custom progress bar to visualize the percentage of completed tasks. The approach I am taking involves using v-bind:styles and passing {width: dynamicWidth + '%'} to regulate the progression of the bar. To ac ...

When the progress bar is clicked, the background color changes and then changes back again

https://www.w3schools.com/code/tryit.asp?filename=FG1ZE0NJ4ZX7 https://i.stack.imgur.com/Bnd0k.png I have created a progress bar that resembles the screenshot provided. When I hover over it, the color changes to green. However, I am looking for assistanc ...