Incorporating Error Management in Controller and Service: A Step-by-Step Guide

Take a look at the structure of my angular application outlined below:

Within my 'firm.html' page, there is a button that triggers the code snippet provided.

Controller

The controller initiates a Service function. The use of generationInProgress in an ng-show function toggles the visibility of a loading icon on the HTML page.

    $scope.generationInProgress = true;

    firmService.processFirm(firmRequest).then(function(response) {      

        window.location.href = "firm/process";          
        $scope.generationInProgress = false;

    });

Firm Service

This service manages Firm operations with the mentioned function.

this.processFirm = function(firmRequest) {      
    return httpService.put('firm/process', firmRequest);
};

HTTP Service

This service handles all service calls for multiple services, including firmService. Below is the put method being referenced.

this.put = function(url, data) {

    return promise = $http.post(url, data).success(function(response) { 
        return response;
    }).error(function(response) {
        console.log("error");
    });

};

In case of a HTTP error code from the server, the .error function is executed. If there was a dedicated error page, a redirect could be initiated to that page.

However, the challenge lies in displaying the error on the 'firm.html' page while also resetting $scope.generationInProgress to hide the loading icon. This task cannot be handled within httpService due to its generic usage across various components.

I am uncertain about how to transmit the error back to the controller to achieve this goal. Would inserting return response; in both .success and .error functions and then utilizing an IF statement in the controller suffice to check for the HTTP code? Are there other methods worth exploring?

Any insights or suggestions would be greatly valued.

Answer №1

The use of the .success and .error methods has been deemed outdated. It is recommended to utilize the .then and .catch methods instead.

When chaining a successful promise, make sure to return data to the .then method. For a rejected promise, remember to throw the error response:

this.put = function(url, data) {

    //Implementing the .then method
    return promise = $http.post(url, data).then(function(response) {
        //Returning for success chaining 
        return response;
    //Using the .catch method
    }).catch(function(response) {
        console.log("error");
        //Throwing for rejection chaining
        throw response;
    });

};

According to the Documentation1:

Deprecation Notice

The traditional promise methods like .success and .error within $http have now been deprecated. It is advised to switch to using the standard .then method.

Answer №2

To manage the rejected state, you can handle it within the controller and then present it in a customized way on the HTML page.

$scope.generationInProgress = true;
$scope.error = "";

firmService.processFirm(firmRequest).then(function(response) {      
    window.location.href = "firm/process";          
    $scope.generationInProgress = false;

}, function(err) {
    $scope.generationInProgress = false;
    $scope.error = "Your personalized error message: " + err;
});

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

Guide on how to store a CSS image in a server using PHP

Looking to create a button generator using JavaScript on my website, similar to the one found here http://css-tricks.com/examples/ButtonMaker/. In addition to generating buttons, I also want to include a save button so that users can save the button image ...

Switch between visibility of objects with toggle button

I have set a background image on the body, and positioned a large box, footer, navigation bar, and header above it. In order to add functionality to slide these elements up and down, I've created two buttons with classes 'slideUp' and &apos ...

preserving the current state even after refreshing the page

Currently, I am teaching myself React. When I click on the favorites button, which is represented by a heart symbol, it changes color. However, upon refreshing the page, the color change disappears. To address this issue, I came across the following helpfu ...

What is the best way to modify the state of a nested component?

I am facing a challenge in my React project where I have two buttons in my App.js. When either of the buttons is clicked, I want to change the current state (list) to display in descending order based on the button pressed (order by date or order by upvo ...

Choose ng-change within the table

I've searched everywhere for an answer to this, but I couldn't find it. I have a table that contains select and date input fields. <table id="tblCorrAction" class="table table-bordered table-striped table-hover table-condensed"> <t ...

Effective way to manage Angular scope without resorting to $parent.$parent

After doing some research, I have not been able to find a solution that addresses my particular issue. Here is what I know: ng-if and ng-repeat create isolated scopes. Avoid using $parent.someProperty. Using $parent.$parent.someProperty is strongly disc ...

The Push Over Menu is malfunctioning and not functioning properly

I am facing an issue with pushing my menu along with the content to the right. The JS code I have is not working as expected. When I click on <div class="menu-btn toggle"></div>, the menu does not trigger. Can someone help me understand why thi ...

Encountered a 'File is not defined' error in JavaScript when running code from the node.js command line

I'm encountering an issue with my JavaScript code that is supposed to read a file and print it on the console. Despite having the file test.txt in the same path, I keep getting an error saying "File is not defined." Below is the snippet of the code: ...

The dynamic loading of videos through the YouTube API

-Need to load multiple videos onto a page, keeping it simple -Each video has an ID stored in the database accessed via $slide['message'] -Currently only loading one video successfully, others show up as blank -Code is within a loop, attempt ...

Change the background color of the MUI ToggleButton that is currently selected

I need help figuring out how to change the background color of a selected toggle button. Currently, the buttons are functional but do not visually indicate when one is selected. I would like the first button (Btn 1) to have a default color, and if the us ...

Instead of only one menu icon, now there are three menu icons displayed on the screen. (Additionally, two more divs containing

When visiting on a smartphone browser, you may notice that instead of one menu icon, three icons appear. Upon inspecting the elements, you will find that there are three div's that look like this: <div class="responsive-menu-icon">&l ...

I find the JSX syntax to be quite perplexing

While examining some code, I came across the following: const cardSource = { beginDrag(props) { return { text: props.text }; } }; When working with JSX block code or building objects, I usually use {}. The cardSource variable in this co ...

Pattern matching tool for identifying React components with an unlimited number of properties

Currently diving into MDX and experimenting with Regex to extract details on React components from Markdown files. The regex pattern I'm aiming for should: Detect all types of React components This includes identifying the opening tag <Component ...

The result of Ajax is coming back as unclear

I've encountered an issue while trying to upload an image to my server using a POST form and AJAX. Every time I submit the form, my AJAX response shows as undefined in the error box. Here is the Ajax function I am referring to: $('.register_subm ...

Creating a specialized .toString() function for an array

When trying to create a custom .toString() method on the Array prototype, how can you access the actual array that the method is called on? This approach seems to work: Array.prototype.toString = () => 'custom'; "" + [1,2,3]; // 'custom ...

Retrieve JSON information using AJAX

As I am new to JSON and Ajax, the question I have may seem basic. When I try to display data from my JSON object containing 'name', 'task', 'date', and 'status' using Ajax, it does not show up on my page. Below is m ...

Issues with jQuery spinner not currently active

For quite some time, I had this code working perfectly in my Rails application: $(function () { // Modifying the link's icon while the request is in progress $(document).on('click', 'a[data-remote]', function () { ...

Callbacks in Laika tests go untriggered

Meteor.collection.insert() allows for the use of a callback as one of its arguments. To demonstrate, you can start a new Meteor project and execute the following code in the browser's console. my_collection = new Meteor.Collection("myCollection"); my ...

Unexpected behavior encountered in Rails app with unobtrusive JavaScript

I'm facing an issue with my link_to setup. Here's what I have: <%= link_to "Load More", comments_feed_path(@post.id), :id => 'my-link', :remote => true %> In my application.js file, I have the following code: $( document ...

Struggling to establish a functioning proxy in my React and Node application

In the process of developing a react client app with a node.js express backend, I have encountered an issue related to project structure. https://i.sstatic.net/8rID0.png The client app includes a proxy configuration in its package.json file: "proxy": "h ...