What could be causing me to not receive the correct response or error in my AngularJS factory when using .then()?

I am facing an issue in my Angular factory where I need to display an alert when an error occurs.

Here is the code snippet for calling the factory:

gradeService.assignGrade(requestData).then(Controller.populateResponseObject, Controller.error);

The Controller variable simply refers to the current controller with this line of code: var Controller = this.

While attempting to trigger the error on the UI, a 500 Server Error is encountered as expected. However, instead of going to the error function, it goes to the populateResponseObject function. How can I make the service return the error properly?

Below is the relevant part of the service code:

app.factory('gradeService', function ($http) {
    var baseUrl = "http://localhost:8080";

    var add = function (request) {
        var requestUrl = baseUrl + "/grade/new";

        return $http.post(requestUrl, request)
        .then(function (responseSuccess) {
            return responseSuccess.data;
        },
        function (responseError) {
            return responseError.data;
        });
    };

    return {
        assignGrade: add
    };
});

And here is the snippet for handling errors (error):

Controller.error = function (error) {
    // ... some code
    else if(error.status === 500) {
        if(error.exception === "org.springframework.dao.DataIntegrityViolationException") alert("Error: this person has already been graded for this month. Grade was not saved.");
        else if(error.exception === "java.sql.SQLException") alert("Error establishing connection with database. Please try again later.");
        else alert("Error: " + error.message + ": Generic Server Error.");
    }
};

I am using Spring for the backend implementation.

Any suggestions or assistance would be greatly appreciated.

Answer №1

The issue at hand is that the assignGrade()/add() function does not return a promise, but rather the response data. This means that Angular will not properly handle promises.

To resolve this, simply make the following changes:

app.factory('gradeService', function ($http) {

    var baseUrl = "http://localhost:8080";

    var add = function (request) {
        var requestUrl = baseUrl + "/grade/new";

        return $http.post(requestUrl, request);
    };

    return {
        assignGrade: add
    };
});

Answer №2

If you want to connect errors together, simply pass it back to the onRejected function.

app.factory('gradeService', function ($http) {

    var baseUrl = "http://localhost:8080";

    var add = function (request) {
        var requestUrl = baseUrl + "/grade/new";

        return $http.post(requestUrl, request)
        .then(function onFulfilled(responseSuccess) {
            return responseSuccess.data;
        },
        function onRejected (responseError) {
            //to chain rejection throw it
            throw responseError;
            //Not return
            //return responseError.data;
        });
    };

    return {
        assignGrade: add
    };
});

When you return something from an onRejected handler, it changes the promise outcome to fulfilled.

To learn more, visit Angular execution order with $q.

Answer №3

It's important to remember that handling promises should be done in the controller, not in the service.

app.factory('GradeService', function ($http) {
    var obj = {}
    var baseUrl = "http://localhost:8080";

    obj.add = function (request) {
        var requestUrl = baseUrl + "/grade/new";

        return $http.post(requestUrl, request);
    };

    return obj;
});

I believe the code provided above will help resolve your issue.

Answer №4

To start, make changes to the factory setup:

app.factory('gradeService', function ($http) {

    var baseUrl = "http://myserver:3000";

    var addGrade = function (requestData) {
        var requestUrl = baseUrl + "/grades/add";

         return $http.post(requestUrl, requestData);
    };

    return {
        saveGrade: addGrade
    };
});

Next, use the factory in your code this way:

gradeService.saveGrade(gradeData).then(function(successResponse) {
    // Handle success here...
}, function(errorResponse) {
    // Handle error here...
});

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

The AngularJS controller does not have its array initialized

Creating a small dialog controller where questions, answers, and correct answer index can be added. The goal is to allow users to add multiple questions and save them in an array. Everything works smoothly until attempting to push the JSON data of the que ...

Personalized Pinnacles featuring Angular directive elements displayed on a Bing Maps interface

I've implemented the Bing Maps AJAX Control to showcase a map, and I've crafted an Angular directive specifically for the Pushpins intended on the map: app.directive('myPin', function(){ return { restrict: 'E', ...

Unable to hide jQuery form and receiving undefined function output

I seem to be facing an issue with one of the buttons. It's not functioning properly. Whenever I click on the "Add Run" button followed by the "Home" button, most functions stop working as expected. The dynamically created form doesn't hide, the ...

Alter the color of a single character using JQuery, all while keeping the HTML tags unchanged

I'm currently working on iterating through the DOM using JQuery in order to change the color of every occurrence of the letter m. Here is what I have so far: $(document).ready(function(){ var m = "<span style='color: red;'>m</span& ...

Clicking to enter fullscreen mode on a website will result in the Fullscreen API automatically closing

For my current project, I am creating an offline website and would like it to display in full screen when opened. I have been using the Fullscreen API, but it exits fullscreen mode when a user navigates to another page. After researching the issue, it seem ...

Is it feasible to append an element to the result of a function that returns an array?

Is it possible to push something to an array returned by a function, but not directly? Instead, I want to push it back into the function itself. hierar() { return [{ h: 1 }, { h: 2, hh: [{ u: 2.1 }, { u: 2.2 }] }, { h: 3, hh: [{ u: 4 }, { U: 5 } ...

Encountering an undefined index error while utilizing ajax

My current task involves trying to retrieve data from PHP and display it using jQuery. The issue I am facing is that the data is not being passed from jQuery to PHP successfully. When I use var_dump on the variable $url, it either echoes string'' ...

Please provide the date using the Foundation Datepicker tool

Beginner in JavaScript here! I am having an issue with submitting dates selected using the Foundation Datepicker from . I have searched for solutions on StackOverflow like Post form on select with JQuery Datepick, but none seem to work in my case. If a Ja ...

Utilizing jQuery for array selection

If there's an array of HTML elements with the following structure... let info = [<tr>...</tr>, <tr class="name">...</tr>, <tr class="colour">...</tr>] How can one select only the class name from the info array usi ...

Opt for utilizing variables rather than string values containing relative paths in a TypeScript project

Is it possible to implement a namespace-like structure within a large project for importing modules? For instance, instead of import {formatNumber} from '../../../utils/formatters' Could I use import {formatNumber} from utils.formatters I b ...

Time well spent with The Mighty Ajax

Within the success function for my post, I need to include the time posted. The original PHP code snippet that displays the time looks like this: echo "<br/><a href='#' class='subtleLink' style='font-weight:normal;'& ...

Exploring the foundations of web development with html and stylus

If you have experience with the roots platform, you are familiar with its default stack including jade, stylus, and coffee script. The documentation provides some information on using HTML, CSS, and pure JavaScript instead of the compiled languages, but d ...

Tips for displaying lower quality images while initially downloading higher quality versions

I need to download and display a large image in an img tag. Since the image is not Progressive JPEG, it will render as it downloads. Is there a way to show a low-resolution version of the image while it fetches from the server using only CSS or an HTML p ...

Page redirects automatically after AJAX call

I'm a beginner when it comes to using AJAX and I am trying to delete a student from a list through an AJAX request. I want the response of the request to be displayed on the same page within a specific div, but instead, the response keeps redirecting ...

Having trouble with an Ajax request in jQuery

Need some help with the code below - I can't seem to get the success or error event to fire. Even though the server returns a 200 OK response with the required data. Any assistance would be greatly appreciated! $('body').on('click&apos ...

Cypress' clicking feature does not automatically scroll into view

A new website has been constructed using a combination of Vue/Nuxt and includes SSR, with links located in the footer. During testing, it was discovered that although the link is present and visible, when attempting to click on it, the error message click ...

Automatic closing of multile- vel dropdowns in Bootstrap is not enabled by default

I have successfully implemented bootstrap multilevel dropdowns. However, I am facing an issue where only one child is displayed at a time. <div class="container"> <div class="dropdown"> <button class="btn btn-default dropdown-to ...

Processing multipart form data in a Node.js Express application

I am encountering an issue with sending form data from a reactjs app using axios. Even though the express is properly configured, the req.body appears to be empty. What could be causing this problem? import bodyParser from 'body-parser'; app.use ...

Types of flow. What sets apart type {} from {||}?

I am unsure of the specific distinctions. I am curious about the variations. ...

There is an issue with the left-hand side in this JavaScript

Currently encountering an issue with the code line $('#cps').val() = time;. To clarify, I am aiming to assign the value of variable time to cps instead of comparing them. var amount = 0; $("#cps").click(function() { amount = amount + 1; ...